Spring安全认证过滤器URL被忽略

时间:2016-07-03 10:11:01

标签: java spring spring-security

我想要完成的是基于jwt令牌的身份验证,用于我的其余api。 / 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);
}
}

我的问题是过滤器现在应用于每个网址,而不仅仅是带有/ api前缀的网址。

我意识到我的"配置"方法可能是错误的,但它应该是什么样的?我想要完成的是将过滤器用于/ api路径。

+1问题:为什么有两个值来配置应用过滤器的路径? (一次作为配置中antMatchers方法的参数,然后是构造函数参数" filterProcessesUrl" for AbstractAuthenticationProcessingFilter)。这些值如何相互关联,我应该使用哪一个?

1 个答案:

答案 0 :(得分:1)

问题出在这一部分:

@Override
protected boolean requiresAuthentication(HttpServletRequest request, HttpServletResponse response) {
    return true;
}

我复制了它并且从未意识到它在那里。