JwtAuthencticationEntryPoint没有捕获AuthenticationException

时间:2018-06-14 07:32:19

标签: spring-boot spring-security jwt

我正在使用JsonWebToken处理SpringSecurity。

WebSecurityConfigur是

@Autowired
    private JwtAuthenticationEntryPoint unauthorizedHandler;

    @Bean
public JwtAuthenticationFilter authenticationTokenFilterBean() throws Exception {
    return new JwtAuthenticationFilter();
}

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

            http.cors().and().csrf().disable()
            .authorizeRequests()
            .antMatchers("/","/token/*").permitAll()
            .antMatchers("/soservice").authenticated()
            .and()
            .exceptionHandling().authenticationEntryPoint(unauthorizedHandler).and()
            .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);

            http.addFilterBefore(authenticationTokenFilterBean(), UsernamePasswordAuthenticationFilter.class).exceptionHandling().authenticationEntryPoint(unauthorizedHandler);
        }

以下是从jwt标记获取userName的JwtAuthenticationFilter。

@Override
    protected void doFilterInternal(HttpServletRequest req, HttpServletResponse res, FilterChain chain) throws  IOException, ServletException {
        String header = req.getHeader(HEADER_STRING);
        String username = null;
        String authToken = null;
        if (header != null && header.startsWith(TOKEN_PREFIX)) {
            authToken = header.replace(TOKEN_PREFIX,"");
            try {
                username = jwtTokenUtil.getUsernameFromToken(authToken);

            } catch (IllegalArgumentException e) {
                logger.error("an error occured during getting username from token", e);
            } catch (ExpiredJwtException e) {
                logger.warn("the token is expired and not valid anymore", e);
                throw new BadCredentialsException("the token is expired and not valid anymore",e);
            } catch(SignatureException e){
                logger.error("Authentication Failed. Username or Password not valid.",e );
            }
        } else {
            logger.warn("couldn't find bearer string, will ignore the header");
        }
        if (username != null && SecurityContextHolder.getContext().getAuthentication() == null) {

            UserDetails userDetails = userDetailsService.loadUserByUsername(username);

            if (jwtTokenUtil.validateToken(authToken, userDetails)) {
                UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userDetails, null, Arrays.asList(new SimpleGrantedAuthority("ROLE_ADMIN")));
                authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(req));
                logger.info("authenticated user " + username + ", setting security context");
                SecurityContextHolder.getContext().setAuthentication(authentication);
            }
        }

        chain.doFilter(req, res);
    }

**我正面临以下问题。

在上面的代码中,只要令牌过期,我就会抛出BadCredentialsException。 但JwtAuthencticationEntryPoint没有处理该异常。**

JwtAuthencticationEntryPoint如下

@Override
    public void commence(HttpServletRequest request,
                         HttpServletResponse response,
                         AuthenticationException authException) throws IOException {
        response.setStatus(401);
        response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Unauthorized");
}

非常感谢任何帮助。 提前谢谢。

0 个答案:

没有答案