我想使用我的自定义过滤器来启用spring安全性,但是我发现我无法仅在控制器中定义的路径上启用它。
这是我当前的SecurityConfiguration:
@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);
}
}
在我的控制器中,我有/api/v1/user
,/api/v1/user/{userId}
。当我尝试访问无效路径时/api/v1/invalid
,我总是得到401而不是404,因为任何以/api/v1
开头的路径都将首先通过AuthenticationFilter。当我尝试在现有路径上使用不受支持的HTTP方法时,也会发生这种情况,我的应用程序将返回401而不是405。
我想实现在控制器级别上添加注释(或方法级别也可以,并且仅在该控制器中定义的路径上应用身份验证过滤器,例如]
@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方法级别限制,则也必须指定它。