我想使用自定义过滤器启用 Spring Security,但我发现我无法仅在 Controller 中定义的路径上启用它。
这是我当前的安全配置:
@Configuration
@EnableWebSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable().sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and()
.antMatcher("/api/v1/**").addFilterBefore(
new AuthenticationFilter(myAuthenticator()),
ChannelProcessingFilter.class);
}
}
在我的 Controller 中,我有 /api/v1/user
、/api/v1/user/{userId}
。当我尝试访问无效路径时,例如/api/v1/invalid
,我总是得到 401 而不是 404,因为任何以 /api/v1
开头的路径都会首先经过 AuthenticationFilter。当我尝试在现有路径上使用不受支持的 HTTP 方法时也会发生这种情况,我的应用程序将返回 401 而不是 405。
我想实现诸如在 Controller 级别添加注释(或方法级别也可以)之类的目标,并仅在该 Controller 中定义的路径上应用身份验证过滤器,例如
@WhateverAnnotationWillAddFilterToThisController***
@RestController
@RequestMapping(value = "/api/v1", produces = "application/json")
public interface LicensingController {
@RequestMapping(value = "user", method = RequestMethod.POST)
public ResponseEntity<?> user();
@RequestMapping(value = "user/{userId}", method = RequestMethod.GET)
public ResponseEntity<LicensingRequest> getUser(
@PathVariable
String userId);
}
如有任何建议,我们将不胜感激。谢谢!
最佳答案
该行为是正确且一致的,因为您使用 /api/v1/**
来确保安全,这是一条更广泛的路径。理想情况下,AuthenticationFilter
始终位于资源路径之上,以避免在未经身份验证的情况下访问资源。
为了得到 404,你所做的就是使用更窄的路径匹配。
@Configuration
@EnableWebSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable().sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and()
.antMatchers("/api/v1/user", "/api/v1/user/{userId}").addFilterBefore(
new AuthenticationFilter(myAuthenticator()),
ChannelProcessingFilter.class);
}
}
如果您想要 http 方法级别限制,则也必须指定。
关于java - 如何仅在特定 Controller 中定义的路径上启用 Java Spring 安全性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60178071/