【发布时间】:2020-07-17 23:25:02
【问题描述】:
我有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 ...
}
【问题讨论】:
标签: java authentication spring-security authorization jwt-auth