如何在JWT过滤器中添加API到白名单中

huangapple 未分类评论45阅读模式
英文:

How do i whitelist api in JWT Filter

问题

我有一个名为SpringSecurityWebAppConfig的类,它使用了我自己的过滤器类JwtAuthenticationFilter

现在的问题是,如何绕过我的JwtAuthenticationFilter,以便针对没有请求头和/或令牌的 API 调用。我是否应将其设置为可配置项,并在过滤器中读取它?

我的JwtAuthenticationFilter是从另一个库导入的类。其目的是为了在其他微服务中重用该文件。

示例:

/scanFile 不需要请求令牌。当我将其添加到 SpringSecurityWebAppConfig 中时,我的过滤器会抛出 401 错误,因为它没有请求令牌。

SpringSecurityWebAppConfig 类:

public class SpringSecurityWebAppConfig extends WebSecurityConfigurerAdapter {
    
    @Autowired
    public JwtAuthenticationFilter jwtAuthenticationFilter;
    
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().disable()
            .authorizeRequests()
            .antMatchers("/homePage").access("hasRole('ROLE_USER') or hasRole('ROLE_ADMIN')")
            .antMatchers("/userPage").access("hasRole('ROLE_USER')")
            .antMatchers("/adminPage").access("hasRole('ROLE_ADMIN')")
            .antMatchers(HttpMethod.DELETE, "/data").access("hasRole('ROLE_ADMIN')")
            .antMatchers("/login").permitAll()
            .antMatchers("/logout").authenticated()
            .and()
            .anonymous().disable()
            .exceptionHandling()
            .authenticationEntryPoint(new CustomAuthenticationEntryPoint())
            .and()
            .headers()
            .httpStrictTransportSecurity()
            .includeSubDomains(true).maxAgeInSeconds(31536000);

    
        // Add a filter to validate the tokens with every request
        http.addFilterBefore(jwtAuthenticationFilter, UsernamePasswordAuthenticationFilter.class);
    }
}

JwtAuthenticationFilter 类:

private void getJwtFromRequest(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
    
          
    String bearerToken = request.getHeader("Authorization");
    
    // Step 1: Check if bearer token exist in authorization header and if bearer token start with "Bearer "
    if (!StringUtils.hasText(bearerToken) || !bearerToken.startsWith("Bearer ")) {
    
        String errorMsg = "No access token found in request headers.";
    
        Error err = new Error(JWT_AUTHENTICATION_FILTER, "AccessTokenMissingException", errorMsg);
    
        // Java object to JSON string
        String jsonString = mapper.writeValueAsString(err);
    
        log.error(jsonString);
    
        throw new AccessTokenMissingException(errorMsg);
    }

    //rest of the processing here ...
}
英文:

I have SpringSecurityWebAppConfig class that uses my own filter class JwtAuthenticationFilter.

The question now is how do i bypass my JwtAuthenticationFilter for api calls that does not have request header and/or token. Do I set it as a configurable and read it in the filter?

My JwtAuthenticationFilter is an imported class from another library. The purpose is to reuse the file for the other microservices.

Example:

/scanFile does not need request token. When I add into SpringSecurityWebAppConfig. My filter is throw 401 as it does not have request token.

SpringSecurityWebAppConfig class:

public class SpringSecurityWebAppConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    public JwtAuthenticationFilter jwtAuthenticationFilter;

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().disable()
            .authorizeRequests()
            .antMatchers("/homePage").access("hasRole('ROLE_USER') or hasRole('ROLE_ADMIN')")
            .antMatchers("/userPage").access("hasRole('ROLE_USER')")
            .antMatchers("/adminPage").access("hasRole('ROLE_ADMIN')")
            .antMatchers(HttpMethod.DELETE, "/data").access("hasRole('ROLE_ADMIN')")
            .antMatchers("/login").permitAll()
            .antMatchers("/logout").authenticated()
            .and()
            .anonymous().disable()
            .exceptionHandling()
            .authenticationEntryPoint(new CustomAuthenticationEntryPoint())
            .and()
            .headers()
            .httpStrictTransportSecurity()
            .includeSubDomains(true).maxAgeInSeconds(31536000);


        // Add a filter to validate the tokens with every request
        http.addFilterBefore(jwtAuthenticationFilter, UsernamePasswordAuthenticationFilter.class);
    }
}

JwtAuthenticationFilter Class:

 private void getJwtFromRequest(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {

      
            String bearerToken = request.getHeader("Authorization");

            // Step 1: Check if bearer token exist in authorization header and if bearer token start with "Bearer "
            if (!StringUtils.hasText(bearerToken) || !bearerToken.startsWith("Bearer ")) {

                String errorMsg = "No access token found in request headers.";

                Error err = new Error(JWT_AUTHENTICATION_FILTER, "AccessTokenMissingException", errorMsg);

                // Java object to JSON string
                String jsonString = mapper.writeValueAsString(err);

                log.error(jsonString);

                throw new AccessTokenMissingException(errorMsg);
            }

//rest of the processing here ...
}

答案1

得分: 0

所以您想在没有Spring Security身份验证的情况下对某些API进行白名单处理?

您可以在SpringSecurityWebAppConfig中使用web.ignoring().antMatchers(),将这些URL从Spring Security中排除。

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

so you want to whitelist some apis even without spring security authentication?

you can use web.ignoring().antMatchers() in your SpringSecurityWebAppConfig, to exclude the urls from spring security.

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

huangapple
  • 本文由 发表于 2020年4月6日 09:35:37
  • 转载请务必保留本文链接:https://java.coder-hub.com/61051744.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定