Java 忽略Spring安全身份验证筛选器url
我试图为我的RESTAPI实现一个基于jwt令牌的身份验证。 /api下的所有内容都只能通过令牌访问 我的web安全配置中有以下配置方法:Java 忽略Spring安全身份验证筛选器url,java,spring,spring-security,Java,Spring,Spring Security,我试图为我的RESTAPI实现一个基于jwt令牌的身份验证。 /api下的所有内容都只能通过令牌访问 我的web安全配置中有以下配置方法: @Override protected void configure(HttpSecurity http) throws Exception { http .authenticationProvider(authenticationProvider()) .csrf().disable() .autho
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authenticationProvider(authenticationProvider())
.csrf().disable()
.authorizeRequests().antMatchers("/api/**").authenticated()
.and()
.exceptionHandling()
.authenticationEntryPoint(authenticationEntryPoint())
.and()
.addFilterBefore(authenticationFilter(),BasicAuthenticationFilter.class)
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
}
这是过滤器:
public class JwtAuthenticationFilter extends AbstractAuthenticationProcessingFilter {
public JwtAuthenticationFilter(AuthenticationManager manager) {
super("/api/**");
this.setAuthenticationManager(manager);
}
@Override
protected boolean requiresAuthentication(HttpServletRequest request, HttpServletResponse response) {
return true;
}
@Override
public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {
String header = request.getHeader("Authorization");
if (header == null || !header.startsWith("Bearer ")) {
throw new JwtTokenMissingException("No JWT token found in request headers");
}
String authToken = header.substring(7);
JwtAuthenticationToken authRequest = new JwtAuthenticationToken(authToken);
return getAuthenticationManager().authenticate(authRequest);
}
@Override
protected void successfulAuthentication(HttpServletRequest request, HttpServletResponse response, FilterChain chain, Authentication authResult)
throws IOException, ServletException {
super.successfulAuthentication(request, response, chain, authResult);
chain.doFilter(request, response);
}
}
我的问题是,过滤器现在应用于每个url,而不仅仅是带有/api前缀的url
我知道我的“configure”方法可能是错误的,但它应该是什么样子呢?我想要完成的就是对/api路径使用过滤器
+1问题:为什么有两个值来配置将应用筛选器的路径?(一次作为配置中antMatchers方法的参数,然后作为AbstractAuthenticationProcessingFilter的构造函数参数“FilterProcessURL”)。这些值如何相互关联,我应该使用哪一个?问题在于这一部分:
@Override
protected boolean requiresAuthentication(HttpServletRequest request, HttpServletResponse response) {
return true;
}
我复制了它,但从未意识到它在那里。我想如果你在
之前添加.antMatcher(“/api/**”)
,在之前添加过滤器,你的问题也会得到解决。