如何从spring安全认证中删除url模式?

kulphzqa  于 2021-07-16  发布在  Java
关注(0)|答案(2)|浏览(322)

我需要允许绕过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();
}
qxsslcnc

qxsslcnc1#

问题是你添加了 .authorizeRequests() 顺序不对。 authorizeRequests() 秩序很重要 .authenticated() 必须先来。

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

moiiocjp2#

我通常在 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();
}

相关问题