如何从 spring 安全身份验证中删除 url 模式?

时间:2021-03-17 13:48:42

标签: java spring spring-security

我需要允许绕过 Spring Security 身份验证访问特定控制器,但我不确定为什么 Spring Security 仍将这些 URL 视为受保护的。我注意到了这个问题,因为每次我收到 401 响应。

在调试模式下,我检查了请求仍在由 restAuthenticationFilter() 提供的过滤器处理,即使这些理论上是公共 URL。

谁能猜到我做错了什么吗?

感谢您的帮助

我的配置类:

class SecurityConfig extends WebSecurityConfigurerAdapter {

  private static final RequestMatcher PUBLIC_URLS = new OrRequestMatcher(new AntPathRequestMatcher("/authentication/**"));
  private static final RequestMatcher PROTECTED_URLS = new NegatedRequestMatcher(PUBLIC_URLS);

  @Override
  public void configure(final WebSecurity web) {
    web
      .ignoring()
        .requestMatchers(PUBLIC_URLS)
        .antMatchers("/v2/api-docs",
            "/configuration/ui",
            "/swagger-resources/**",
            "/configuration/security",
            "/swagger-ui.html",
            "/webjars/**",
            "/authentication/**");
  }

  @Override
  protected void configure(final HttpSecurity http) throws Exception {
    http
      .sessionManagement()
        .sessionCreationPolicy(STATELESS)
        .and()
      .exceptionHandling()
        // this entry point handles when you request a protected page and you are not yet
        // authenticated
        .defaultAuthenticationEntryPointFor(forbiddenEntryPoint(), PROTECTED_URLS)
        .and()
      .authenticationProvider(tokenAuthProv())
      .addFilterBefore(restAuthenticationFilter(), AnonymousAuthenticationFilter.class)
      .authorizeRequests()
        .requestMatchers(PROTECTED_URLS).authenticated()
        .and()
      .csrf().disable()
      .formLogin().disable()
      .httpBasic().disable()
      .logout().disable();
  }

... some other beans

我的控制器

@RestController
@RequestMapping("/authentication")
@FieldDefaults(level = PRIVATE, makeFinal = true)
@AllArgsConstructor(access = PACKAGE)
final class AuthenticationController {
  @NonNull
  IUserAuthenticationService authservice;
  @Autowired
  GerenciadorUsuariosIntegracao users;

  @PostMapping("/login")
  @ApiResponses(value = {
            @ApiResponse(code=400, message = "Bad Request", response = ExceptionResponse.class),
            @ApiResponse(code=401, message = "Unauthorized", response = ExceptionResponse.class),
            @ApiResponse(code=200, message = "OK", response = SuccessLoginResponse.class)
     })
  ResponseEntity<Object> login(@RequestBody UsuarioAPI usuario) {
      
     LocalDateTime horaAtual = LocalDateTime.now(ZoneId.of("America/Sao_Paulo"));
     Optional<String> token =  authservice.login(usuario.username, usuario.password);
     if (token.isPresent()) {
        SuccessLoginResponse sucessResponse = new SuccessLoginResponse(horaAtual, token.get());
        return new ResponseEntity<Object>(sucessResponse, HttpStatus.OK);
     }
     else { 
        ExceptionResponse exceptionResponse = new ExceptionResponse(horaAtual.toLocalTime(), "credenciais inválidas");
        return new ResponseEntity<Object>(exceptionResponse, HttpStatus.FORBIDDEN);
     }
  }
  
  @PostMapping("/registrarusuario")
  String register(@RequestBody UsuarioAPI usuario) {
      ApiUser usuariopersistido = (ApiUser) users.registrarNovoUsuario(usuario);
    return usuariopersistido.toString();
  }
}

我也尝试了推荐的第一种方法......结果还是一样

protected void configure(final HttpSecurity http) throws Exception {
        final String[] SWAGGER_AUTH_WHITELIST = {
                "/v2/api-docs",
                "/configuration/ui",
                "/swagger-resources/**",
                "/configuration/security",
                "/swagger-ui.html",
                "/webjars/**",
                "/authentication/**"
        };  
    
    http
      .sessionManagement()
        .sessionCreationPolicy(STATELESS)
        .and()
      .exceptionHandling()
        // this entry point handles when you request a protected page and you are not yet
        // authenticated
        //.defaultAuthenticationEntryPointFor(forbiddenEntryPoint(), PROTECTED_URLS)
        .and()
      .authenticationProvider(tokenAuthProv())
      .addFilterBefore(restAuthenticationFilter(), AnonymousAuthenticationFilter.class)
      .authorizeRequests()
        .mvcMatchers("/authentication/login").permitAll()
        .mvcMatchers("/authentication/registrarusuario").permitAll()
        .mvcMatchers(SWAGGER_AUTH_WHITELIST).permitAll()
        //.requestMatchers(PROTECTED_URLS)
      .anyRequest()
        .authenticated()
        .and()
      .csrf().disable()
      .formLogin().disable()
      .httpBasic().disable()
      .logout().disable();
} 

2 个答案:

答案 0 :(得分:1)

问题是您以错误的顺序添加了 .authorizeRequests()authorizeRequests() 顺序很重要,.authenticated() 必须在前。

.authorizeRequests().anyRequest().authenticated()
.and()
.authorizeRequests().antMatchers("/authentication/login").permitAll()
.and()
....

答案 1 :(得分:0)

我通常在具有 configure 参数的 HttpSecurity 方法中配置这些端点。您可以根据 HTTP 方法配置要允许的端点列表或子集:

@Override
protected void configure(final HttpSecurity http) throws Exception {
    final String[] SWAGGER_AUTH_WHITELIST = {
            "/swagger-ui/**",
            "/swagger-resources/**",
            "/v3/api-docs",
    };

    // Set permissions on endpoints
    http.authorizeRequests()
            // public endpoints (e.g. Swagger)
            .mvcMatchers("/login").permitAll()
            .mvcMatchers(SWAGGER_AUTH_WHITELIST).permitAll()
            .mvcMatchers(HttpMethod.GET, "/products/**").permitAll()
            .mvcMatchers(HttpMethod.POST, "/users").permitAll()
            // private endpoints
            .anyRequest().authenticated();
}