簡體   English   中英

Spring Security 繞過 URL 或過濾器

[英]Spring Security bypass URL or Filter

我有一個僅公開 REST API 的 Spring Boot 應用程序。 我需要保護它,並且我正在使用基於令牌的方法 - 特別是 JWT。

到目前為止,這是我實施的:

//
// The Spring Security configuration class
@EnableGlobalAuthentication
public class SecurityConfig extends WebSecurityConfigurerAdapter {
  @Override
  protected void configure(final HttpSecurity http) throws Exception {
    http
        .csrf().disable()
        .authorizeRequests()
          .antMatchers("/api/login", "/api/logout").permitAll()
          .antMatchers("/api/**").authenticated()
          .anyRequest().authenticated()
        .and()
          .addFilterBefore(new JwtFilter(), BasicAuthenticationFilter.class)
          .sessionManagement()
          .sessionCreationPolicy(SessionCreationPolicy.STATELESS);
  }
}

//
// The JWT filter class to check for the token in the HTTP request (headers)
public final class JwtFilter extends GenericFilterBean {
  private final Logger logger = LoggerFactory.getLogger(this.getClass());

  @Override
  public void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain chain) throws
      IOException, ServletException {
    final HttpServletRequest req = (HttpServletRequest)request;
    final String header = req.getHeader("Authorization");

    logger.debug("{} {}", req.getMethod(), req.getRequestURI());
    if ((null == header) || !header.startsWith("Bearer ")) {
      logger.debug("Missing or invalid Authorization header");
    }
    try {
      // Check the token here; the implementation is not relevant here
      /*SecurityContextHolder.getContext()
          .setAuthentication(manager.authenticate(new JwtToken(JWTParser.parse(header.substring(7)))));*/
      chain.doFilter(request, response);
    } catch (final AuthenticationException e) {
      SecurityContextHolder.clearContext();
      // Do some other stuff here
    } catch (final ParseException e) { /* ... */ }
  }
}

問題是過濾器對每個 URI 都正確執行,但我希望能夠從同一組中排除某些端點。 我的 API 被放置在這個上下文/api/* ,我想排除,例如, /api/login/api/logout

注意:我的 Spring Boot application.yml文件沒有啟用/修改任何安全相關功能的設置。

將為通過 HttpSecurity 配置的所有端點執行過濾器。 如果您不希望對某些端點應用過濾器,請將它們包含在配置 WebSecurity 的方法中。 例如,

@Override
public void configure(WebSecurity web) throws Exception {
    web
      .ignoring()
        .antMatchers("/api/login", "/api/logout");
}

請閱讀這篇文章了解更多詳情。

我正在做與解決方案中提到的相同的事情

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.cors()
        .and().csrf().ignoringAntMatchers("/api/auth/**").disable()
        .exceptionHandling().authenticationEntryPoint(unauthorizedHandler)
        .and().sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
        .and().authorizeRequests()
        .antMatchers("api/content/**").permitAll()
        .anyRequest().authenticated();
        
        http.addFilterBefore(authenticationJwtTokenFilter(), UsernamePasswordAuthenticationFilter.class);
    }
    @Override
    public void configure(WebSecurity web) throws Exception {
        web.ignoring().antMatchers("api/auth/signup");
    }

每個注冊請求仍然命中doFilterInternal()方法,這是一個自定義方法。

在調試模式下運行EnableWebSecurity ,我得到:

安全過濾器鏈:[WebAsyncManagerIntegrationFilter
安全上下文持久性過濾器
HeaderWriterFilter
過濾器
注銷過濾器
AuthToken過濾器
請求緩存感知過濾器
SecurityContextHolderAwareRequestFilter
匿名身份驗證過濾器
會話管理過濾器
異常翻譯過濾器
過濾器安全攔截器]

我該怎么做才能解決這個問題?

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM