![](/img/trans.png)
[英]spring security UsernamePasswordAuthenticationFilter url match issue
[英]Spring Boot Security UsernamePasswordAuthenticationFilter does not limit the login url to only POST
我查看了整个过程,没有其他人遇到这个我能找到的问题。 身份验证工作正常,但登录 url 适用于任何 HTTP 方法(GET、PUT 等),而不是仅适用于 POST。 我尝试手动设置filter.setPostOnly(true);
在我制作的自定义 JWTAuthenticationFilter 上,但它仍然允许所有方法。
@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
private static final String FILTER_PROCESS_URL = "/authentication";
private static final String HEALTH_RESOURCE_URL = "/health/**";
private CustomUserDetailService userDetailsService;
private BCryptPasswordEncoder bCryptPasswordEncoder;
public WebSecurityConfig(CowCalfUserDetailService userDetailsService, BCryptPasswordEncoder bCryptPasswordEncoder) {
this.userDetailsService = userDetailsService;
this.bCryptPasswordEncoder = bCryptPasswordEncoder;
}
@Override
protected void configure(HttpSecurity httpSecurity) throws Exception {
httpSecurity
.cors().and().csrf().disable().authorizeRequests()
.antMatchers(HttpMethod.POST, FILTER_PROCESS_URL).permitAll()
.antMatchers(HttpMethod.GET, HEALTH_RESOURCE_URL).permitAll()
.anyRequest().authenticated()
.and()
.addFilterBefore(getJWTAuthenticationFilter(), UsernamePasswordAuthenticationFilter.class)
.addFilter(new JWTAuthorizationFilter(authenticationManagerBean()))
// this disables session creation on Spring Security
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
}
@Override
public void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userDetailsService)
.passwordEncoder(bCryptPasswordEncoder);
}
public JWTAuthenticationFilter getJWTAuthenticationFilter() throws Exception {
final JWTAuthenticationFilter filter = new JWTAuthenticationFilter(authenticationManagerBean());
filter.setPostOnly(true);
filter.setFilterProcessesUrl(FILTER_PROCESS_URL);
return filter;
}
}
如果我理解正确,您想将 /authentication 限制为仅 POST Http-Method。 如果是,您可以通过将以下代码片段添加到您的“RestController”中的方法进行身份验证来实现它:
@RequestMapping(value = "/authentication", method = RequestMethod.POST)
我发现了setPostOnly()
是如何工作的。 UsernamePasswordAuthenticationFilter.attemptAuthentication()
在尝试身份验证之前检查 POST 并引发异常。 我已经用我的自定义JWTAuthenticationFilter
覆盖了这个方法。 我只是做了同样的事情,并在我的重写方法中添加了一个检查。 感谢你的建议!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.