Spring-Boot自定义AuthenticationFilter不起作用

时间:2019-03-11 18:53:06

标签: java spring-boot spring-security

我有自定义AuthenticationFilter,它实现了AbstractAuthenticationProcessingFilter接口。我已经设置了AntPathRequestMatcher,但是当我尝试连接以登录其返回值403时,AntPathRequestMatcher无法正常工作

我的过滤器类

public class JWTAuthenticationFilter extends AbstractAuthenticationProcessingFilter {

public JWTAuthenticationFilter() {
    super(new AntPathRequestMatcher("/login", "POST"));
}

    @Override
    public Authentication attemptAuthentication (HttpServletRequest httpServletRequest, HttpServletResponse
    httpServletResponse) throws AuthenticationException, IOException, ServletException {

        String header = httpServletRequest.getHeader("Authorization");


        if (header == null || !header.startsWith("Bearer ")) {
            throw new RuntimeException("Token missing or invalid");
        }

        String authenticationToken = header.substring(7);

        JWTAuthToken token = new JWTAuthToken(authenticationToken);
        return getAuthenticationManager().authenticate(token);
    }

@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);
}
}

配置方法

http.csrf().disable()
            .authorizeRequests()
            .antMatchers(HttpMethod.POST, "/sign-up").permitAll()
            .antMatchers(HttpMethod.POST, "/login").permitAll()
            .anyRequest().authenticated()
            .and()
            .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);

    http.addFilterBefore(authTokenFilter(), UsernamePasswordAuthenticationFilter.class);

    http.headers().cacheControl();

我该如何解决

0 个答案:

没有答案