我正在处理一个过滤器,需要在该过滤器上访问Authorization标头值。当我使用Postman调用API时,我的过滤器可以正常工作,但是当我从前端调用api时,授权请求的值始终为null。我觉得它可能与CORS有关...但是我已经尝试了一些禁用它的方法,但它似乎不起作用。这是我的代码:
我的过滤器
@Component
public class AuthenticationFilter extends OncePerRequestFilter {
@Override
protected void doFilterInternal(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, FilterChain filterChain) throws ServletException, IOException {
String authorizationHeader = httpServletRequest.getHeader("Authorization");
if (authorizationHeader == null || !authorizationHeader.startsWith("Bearer")) {
//TODO Throw error
}
String token = authorizationHeader.substring("Bearer".length()).trim();
validateToken(token);
filterChain.doFilter(httpServletRequest, httpServletResponse);
}
@Override
protected boolean shouldNotFilter(HttpServletRequest request){
String path = request.getServletPath();
return !path.contains("/secured");
}
private void validateToken(String token) {
try {
Jwts.parser()
.setSigningKey(TOKEN_SIGNING_KEY)
.parseClaimsJws(token)
.getBody()
.getExpiration();
} catch (SignatureException | ExpiredJwtException e) {
//TODO Throw error
}
}
}
当我进行调试时,由于我的变量授权为null,所以在获取子字符串时会引发异常。我还尝试了一些配置,这些配置是:
我的配置
@Configuration
public class MyConfiguration {
@Bean
public WebMvcConfigurer corsConfigurer() {
return new WebMvcConfigurerAdapter() {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedMethods("HEAD", "GET", "PUT", "POST", "DELETE", "PATCH")
.allowedHeaders("Authorization", "Content-Type")
.exposedHeaders("Authorization", "Content-Type");
}
};
}
使用axios的JavaScript调用:
axios.request({
url: url,
method: 'put',
headers: {'Content-Type': 'application/json', 'Authorization': token},
data:{
email: email,
firstName: userFirstName,
lastName: userLastName,
phoneNumber: this.phoneNumber
}
}).then(response => this.handleSaveChanges(response));
我已经在发送令牌之前立即打印了令牌,它不是null。我重复一遍,当我从Postman调用API时,我的过滤器工作正常,并且可以访问授权标头。所以我不确定是什么原因引起的。