为了账号安全,请及时绑定邮箱和手机立即绑定

Spring Security中未触发JWT身份验证过滤器

Spring Security中未触发JWT身份验证过滤器

慕雪6442864 2021-04-08 17:13:16
我已经为Spring Rest后端创建了JWT身份验证过滤器。创建JWT似乎不是问题,但是对于我当前的设置,任何请求都经过了身份验证,尽管客户端没有在标头中传递任何令牌,但是没有任何请求会触发401。我已经设置好所有请求都需要授权。我的JwtAuthenticationEntryPoint符合预期:抛出一般401错误。我的JwtAuthenticationFilter:@Componentpublic class JwtAuthenticationFilter extends OncePerRequestFilter {@Autowiredprivate JwtTokenProvider tokenProvider;@Autowiredprivate CustomUserDetailsService customUserDetailsService;private static final Logger logger = LoggerFactory.getLogger(JwtAuthenticationFilter.class);@Overrideprotected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain        filterChain) throws ServletException, IOException {    logger.debug("Filtering request for JWT header verification");    try {        String jwt = getJwtFromRequest(request);        if (StringUtils.hasText(jwt) && tokenProvider.validateToken(jwt)) {            String username = tokenProvider.getUserIdFromJWT(jwt);            UserDetails userDetails = customUserDetailsService.loadUserByUsername(username);            UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken                    (userDetails, null, userDetails.getAuthorities());            authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));            SecurityContextHolder.getContext().setAuthentication(authentication);        }    } catch (Exception ex) {        logger.error("Could not set user authentication in security context", ex);    }    filterChain.doFilter(request, response);}private String getJwtFromRequest(HttpServletRequest request) {    logger.debug("Attempting to get token from request header");    String bearerToken = request.getHeader("Authorization");    if (StringUtils.hasText(bearerToken) && bearerToken.startsWith("Bearer ")) {        return bearerToken.substring(7, bearerToken.length());    }    return null;} }
查看完整描述

1 回答

  • 1 回答
  • 0 关注
  • 403 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信