如何从WebSecurityConfigurerAdapter删除身份验证

时间:2020-03-31 01:03:10

标签: spring spring-security

我下面有一个使用antMatchers从公共端点删除身份验证的类。 但是,公共端点也被阻止,我不断收到HTTP / 1.1 401。 谁能帮我找出下面的问题吗?

@Configuration
@EnableWebSecurity
public class WebSecurity extends WebSecurityConfigurerAdapter {

@Autowired
private UsersService usersService;

@Autowired
private UsersRepository usersRepo;    

@Bean
public BCryptPasswordEncoder bCryptPasswordEncoder()
{
    return new BCryptPasswordEncoder();
}

@Override
protected void configure(HttpSecurity http) throws Exception {
    http.cors().and().csrf().disable();
    http.authorizeRequests().antMatchers(HttpMethod.POST, "/public").permitAll()
        .anyRequest().authenticated()                
        .and().addFilter(getAuthenticationFilter());        
}

@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
    auth.userDetailsService(usersService).passwordEncoder(bCryptPasswordEncoder());
}

private AuthenticationFilter getAuthenticationFilter() throws Exception {
    final AuthenticationFilter filter = new AuthenticationFilter(authenticationManager(), 
     usersService);
    return filter;
}

}

---------------更新1 -------------------

我尝试使用curl使用http POST并返回以下内容。 似乎该请求被捕获到某处,但未在我尝试访问的控制器中捕获:

$ curl -X POST  http://localhost:8083/public -H 'Content-Type:     
application/json' -H 'cache-control: no-cache' -d '{  
"email":"test2@test.com", "password":"12345678" }' -v

*   Trying ::1:8083...
* Connected to localhost (::1) port 8083 (#0)
> POST /user HTTP/1.1
> Host: localhost:8083
> User-Agent: curl/7.69.1
> Accept: */*
> Content-Type: application/json
> cache-control: no-cache
> Content-Length: 51
>
* upload completely sent off: 51 out of 51 bytes
* Mark bundle as not supporting multiuse
< HTTP/1.1 401
< Set-Cookie: JSESSIONID=72AB25425322A17AE7014832D25284FD; Path=/;    
HttpOnly
< X-Content-Type-Options: nosniff
< X-XSS-Protection: 1; mode=block
< Cache-Control: no-cache, no-store, max-age=0, must-revalidate
< Pragma: no-cache
< Expires: 0
< X-Frame-Options: DENY
< WWW-Authenticate: Basic realm="Realm"
< Content-Length: 0
< Date: Tue, 31 Mar 2020 11:36:10 GMT
<
* Connection #0 to host localhost left intact

2 个答案:

答案 0 :(得分:1)

您可能想重写WebSecurity方法,以完全忽略Spring Security处理过程中的/ public路径。

@Override
public void configure(WebSecurity web) throws Exception {
    web.ignoring().antMatchers("/public/**");
}

答案 1 :(得分:0)

很难看到所有代码,但是我怀疑这与配置的authorizeRequests()部分无关。相反,我怀疑是AuthenticationFilter试图对请求进行身份验证,因为您已在请求中包含凭据。缺省值为在AuthenticationConverter返回凭据时尝试进行身份验证。如果提供的凭据无效,AuthenticationFailureHandler将以HTTP 401响应。

要解决此问题,您可以从请求中删除凭据。或者,您可以通过设置requestMatcher来限制调用哪个请求AuthenticationFilter。诸如此类的事情将仅限于处理POST/authenticate

private AuthenticationFilter getAuthenticationFilter() throws Exception {
    final AuthenticationFilter filter = new AuthenticationFilter(authenticationManager(), 
     usersService);
    filter.setRequestMatcher(new AntPathRequestMatcher("/authenticate", "POST"));
    return filter;
}