我在Spring Security的配置上遇到了问题,configure(WebSecurity)方法不能正常工作,以下是我的源代码。
@Override
protected void configure(HttpSecurity http) throws Exception {
http.addFilter(jwtAuthenticationTokenFilter())
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
}
@Override
public void configure(WebSecurity web) {
web.ignoring().antMatchers("/auth",
"/v2/api-docs",
"/swagger-resources/**",
"/configuration/**",
"/swagger-ui.html",
"/webjars/**",
"/", "/refreshconfig", "/*.html", "/*.gif", "/favicon.ico", "/**/*.html", "/**/*.gif",
"/**/*.css", "/**/*.js");
}
public class JwtAuthenticationTokenFilter extends BasicAuthenticationFilter {
private static final Logger log = LoggerFactory.getLogger(JwtAuthenticationTokenFilter.class);
@Autowired
private JwtTokenUtil jwtTokenUtil;
public JwtAuthenticationTokenFilter(JwtTokenUtil jwtTokenUtil, AuthenticationManager authenticationManager) {
super(authenticationManager);
}
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
throws IOException, ServletException {
String token = request.getHeader(JwtTokenUtil.TOKEN_HEADER);
Authentication authentication = null;
try {
if (StringUtils.isNotBlank(token) && token.startsWith(JwtTokenUtil.TOKEN_PREFIX)) {
log.info("JWT found {}", token);
authentication = jwtTokenUtil.getAuthentication(token.replace(JwtTokenUtil.TOKEN_PREFIX, ""));
SecurityContextHolder.getContext().setAuthentication(authentication);
} else if (SecurityContextHolder.getContext().getAuthentication() != null
&& SecurityContextHolder.getContext().getAuthentication().isAuthenticated()) {
log.info("User already authenticated {}",
SecurityContextHolder.getContext().getAuthentication().getPrincipal());
} else {
log.info("Invalid JWT {}", token);
}
filterChain.doFilter(request, response);
} catch (ExpiredJwtException ex) {
response.setContentType("application/json");
response.setStatus(HttpStatus.SC_INSUFFICIENT_SPACE_ON_RESOURCE);
ErrorObj err = new ErrorObj(GamblingErrors.UNAUTHORIZED.getCode(), ex.getMessage());
log.info("OUT ERROR END: {}", err.toString());
response.getOutputStream().println(err.toString());
} catch (UnsupportedJwtException | MalformedJwtException | SignatureException | IllegalArgumentException ex) {
response.setContentType("application/json");
response.setStatus(HttpStatus.SC_UNAUTHORIZED);
ErrorObj err = new ErrorObj(GamblingErrors.UNAUTHORIZED.getCode(), ex.getMessage());
log.info("OUT ERROR END: {}", err.toString());
response.getOutputStream().println(err.toString());
}
}
}
即使有了 configure(WebSecurity web)
方法,仍然是在 configure(HttpSecurity)
适用于所有的资源,不计入所有的资源。web.ignoring
.谁能给我说说为什么不能用?
从你的源码来看,问题并不完整,我可能会建议 弹簧靴 正在把 JwtAuthenticationTokenFilter
类自动进入过滤链。所以,虽然正确地排除了 auth 在 ignoring()
方法,但这还不足以阻止在Spring Boot本身的上下文中发生过滤。解决方案是删除 @Bean
从 jwtAuthenticationTokenFilter()
的方法,或者按照《》中解释的其他方式。春季安全过滤器链不忽略指定路径