当前位置: 首页 > 知识库问答 >
问题:

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

彭琛
2023-03-14

我需要允许绕过spring安全认证访问特定的控制器,但我不确定为什么spring仍然认为这些URL是受保护的……\我注意到了这个问题,因为每次我得到的是401响应

在调试模式下,我检查了restAuthenticationFilter()提供的筛选器仍在处理请求,尽管这些请求理论上是公共URL

有人能猜到我做错了什么吗?

我很感激你的帮助

我的ConfigClass

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();
  }
}



共有1个答案

梁浩涆
2023-03-14

我通常在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();
}
 类似资料:
  • 问题内容: 如何从静态页面的网址中删除? 另外,我需要将任何网址重定向到没有该网址的网址。(即到)。 问题答案: 感谢您的答复。我已经解决了我的问题。假设我的页面在下,则适用以下.htaccess 规则。

  • 所以我编写以下SQL: 但是,有一个错误: 我很困惑因为当我写的时候 null

  • gRPC 被设计成可以利用插件的形式支持多种授权机制。本文档对多种支持的授权机制提供了一个概览,并且用例子来论述对应API,最后就其扩展性作了讨论。 马上将会推出更多文档和例子。 支持的授权机制 SSL/TLS gRP 集成 SSL/TLS 并对服务端授权所使用的 SSL/TLS 进行了改良,对客户端和服务端交换的所有数据进行了加密。对客户端来讲提供了可选的机制提供凭证来获得共同的授权。 OAut

  • 我有一个Spring Boot应用程序,通过将这些依赖项添加到pom.xml中,我用资源服务器来保护它。 这通常工作正常,但我需要从安全检查中排除特定URL,我试图通过创建自定义的WebSecurityConfigureAdapter来实现这一点。 但是,在创建这个类之后,所有调用(除了一个to/test)都将失败,因为服务器将重定向到登录页面。 我的endpoint如下所示: 请求时http:/

  • 问题内容: 我有使用java config方法配置的具有Spring安全性的Spring Web应用程序。我想从身份验证中排除某些URL模式(例如:静态资源等)。我之前用spring security xml config完成了此操作,但是用java config无法弄清,因为添加antmatchers并没有帮助。 以下是我在扩展WebSecurityConfigurerAdapter的安全性配置