(二)添加JwtAuthenticationFilter类实现登录之后在请求头添加 token来访问数据

一、创建JwtAuthenticationFilter类

@Component
public class JwtAuthenticationFilter extends OncePerRequestFilter {

    @Resource
    private JwtUtils jwtUtils;

    @Resource
    private RedisCache redisCache;
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        //1、获取token
        String token = request.getHeader("token");
        if(!StringUtils.hasText(token)){
            //放行
            filterChain.doFilter(request,response);
            //如果不return,那么经过一系列的链条之后,还会运行后面的代码
            return;
        }
        //2、解析token
        String userId;
        try {
            Claims claims = jwtUtils.parseJWT(token);
            userId = claims.getSubject();
        } catch (Exception error) {
            throw new RuntimeException("token异常");
        }
        //3、从redis中获取用户信息
        String redisKey="login:"+userId;
        SecurityUser securityUser=redisCache.getCacheObject(redisKey);
        if(Objects.isNull(securityUser)){
            throw new ServletException("用户未登录");
        }
        //4、存入SecurityContextHolder
        //todo:权限信息还没有
        UsernamePasswordAuthenticationToken authentication
                = new UsernamePasswordAuthenticationToken(securityUser,null,null);
        SecurityContextHolder.getContext().setAuthentication(authentication);

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

二、把JwtAuthenticationFiler添加到过滤器链中

关键代码

//webSecurityConfig
    @Resource
    private JwtAuthenticationFilter jwtAuthenticationFilter;

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

        //添加进过滤器链中
        http.addFilterBefore(jwtAuthenticationFilter, UsernamePasswordAuthenticationFilter.class);

        http.authorizeRequests()
                .mvcMatchers("/login") .permitAll()
                .anyRequest().permitAll();


        http.csrf().disable();
    }

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值