验证失败时,弹簧过滤器链会停止

时间:2020-10-14 08:12:17

标签: java spring spring-boot spring-security jwt

好的,假设我有一个JwtAuthenticationFilter:

public class JwtAuthenticationFilter extends OncePerRequestFilter {

    @Autowired
    //blabla

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        String jwt = extract(request);

        if (StringUtils.hasText(jwt) && tokenVerifier.verify(jwt)) {
            UserCredential user = getUserCredential(jwt, getTokenSigningKey());
            UsernamePasswordAuthenticationToken auth = new UsernamePasswordAuthenticationToken(user, null, buildAuthorities(user));
            SecurityContextHolder.getContext().setAuthentication(auth);
        }

        filterChain.doFilter(request, response);
    }
}

和JwtAuthenticationEntryPoint:

@Component
public class JwtAuthenticationEntryPoint implements AuthenticationEntryPoint {

    @Override
    public void commence(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse,
            AuthenticationException e) throws IOException {
        log.error("Responding with unauthorized error.");
        httpServletResponse.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        httpServletResponse.getWriter().write("Unauthorized");
    }
}

然后是WebSecurityConfig:

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(
        securedEnabled = true,
        jsr250Enabled = true,
        prePostEnabled = true
)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    private static final String[] AUTH_WHITELIST = {
            "/v3/api-docs/**"
    };
    
    @Autowired
    private UserDetailsServiceImpl userDetailsService;

    @Autowired
    private JwtAuthenticationEntryPoint unauthorizedHandler;

    @Bean
    public JwtAuthenticationFilter jwtAuthenticationFilter() {
        return new JwtAuthenticationFilter();
    }

    @Override
    public void configure(AuthenticationManagerBuilder authenticationManagerBuilder) throws Exception {
        authenticationManagerBuilder
                .userDetailsService(userDetailsService)
                .passwordEncoder(passwordEncoder());
    }

    @Bean(BeanIds.AUTHENTICATION_MANAGER)
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {

        ExpressionUrlAuthorizationConfigurer<HttpSecurity>.ExpressionInterceptUrlRegistry registry = http
                .cors().and().csrf().disable()
                .exceptionHandling()
                .authenticationEntryPoint(unauthorizedHandler)
                .and()
                .sessionManagement()
                .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                .and()
                .authorizeRequests()
                // No need authentication.
                .antMatchers(AUTH_WHITELIST).permitAll();

        registry.anyRequest().authenticated();

        // Add our custom JWT security filter
        http.addFilterBefore(jwtAuthenticationFilter(), UsernamePasswordAuthenticationFilter.class);
    }
}

完全没问题。每当我调用任何没有令牌的API(白名单中的除外)时,

commence(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AuthenticationException e)

将被执行,我将看到401响应。完全可以。 但是这里的要点是,执行方法开始后,过滤器链将终止。我的意思是剩下的任何过滤器都不会执行。即使方法开始执行,如何使链连续执行?还是其他任何JWT安全机制都不能停止过滤器链甚至通过身份验证失败?

0 个答案:

没有答案
相关问题