如何在JWT过滤器中列出白名单api



我有一个SpringSecurityWebAppConfig类,它使用我自己的筛选器类JwtAuthenticationFilter

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

我的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 ...
}

所以即使没有spring安全身份验证,你也想将一些api列入白名单?

您可以在SpringSecurityWebAppConfig中使用web.ignoring((.antMatchers((,将url从spring安全中排除。

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

最新更新