token认证过滤器代码实现

HeJin小于 1 分钟Spring全家桶SpringSecurity认证授权

@Component
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {

    @Autowired
    private RedisCache redisCache;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        // 获取token
        String token = request.getHeader("Authorization");
        if (!StringUtils.hasText(token)){
            filterChain.doFilter(request, response);
            return;
        }
        // 解析token
        String userId = null;
        try{
            userId = JwtUtil.parseJWT(token).getSubject();
        } catch (Exception e){
            e.printStackTrace();
            throw new RuntimeException("token非法");
        }
        // redis中获取用户信息
        String redisKey = "login:" + userId;
        LoginUser loginUser = redisCache.getCacheObject(redisKey);
        if (Objects.isNull(loginUser)){
            throw new RuntimeException("用户未登录");
        }
        // 存入SecurityContextHolder
        // TODO 封装权限信息到Authentication中
        Authentication authenticationToken = new UsernamePasswordAuthenticationToken(loginUser, null, null);
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);

        // 放行
        filterChain.doFilter(request, response);
    }
}