【发布时间】:2016-11-05 06:00:45
【问题描述】:
我想要完成的是我的 rest api 的基于 jwt 令牌的身份验证。 /api 下的所有内容都只能通过令牌访问。
我的网络安全配置中有以下配置方法:
@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 前缀的那些。
我知道我的“配置”方法可能是错误的,但它应该是什么样子?我想要完成的就是使用 /api 路径的过滤器。
+1 问题:为什么有两个值来配置将应用过滤器的路径? (曾经作为配置中 antMatchers 方法的参数,然后是 AbstractAuthenticationProcessingFilter 的构造函数参数“filterProcessesUrl”)。这些值如何相互关联,我应该使用哪一个?
【问题讨论】:
标签: java spring spring-security