其他分享
首页 > 其他分享> > 千峰商城-springboot项目搭建-54-拦截器校验Token

千峰商城-springboot项目搭建-54-拦截器校验Token

作者:互联网

1.创建拦截器
@Component
public class CheckTokenInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getParameter("token");
        if (token == null) {
            ResultVO resultVO = new ResultVO(ResStatus.NO, "请先登录", null);
            //提示请先登录
            doResponse(response,resultVO);
            return false;
        } else {
            try {
                //验证token
                JwtParser parser = Jwts.parser();
                parser.setSigningKey("QIANfeng6666");//解析token时的SigningKey必须与设置token时设置的密码一致
                //如果token正确(密码正确,有效期内)则正常执行,否则抛出异常
                Jwt<Header, Claims> claimsJwt = parser.parseClaimsJwt(token);
               

                return true;

            } catch (ExpiredJwtException e) {
                ResultVO resultVO = new ResultVO(ResStatus.NO, "登陆过期", null);
                doResponse(response,resultVO);
            } catch (UnsupportedJwtException e) {
                ResultVO resultVO = new ResultVO(ResStatus.NO, "token不合法", null);
                doResponse(response,resultVO);
            } catch (Exception e) {
                ResultVO resultVO = new ResultVO(ResStatus.NO, "请先登录", null);
                doResponse(response,resultVO);
            }
            return false;

        }
    }
    private void doResponse(HttpServletResponse response,ResultVO resultVO) throws IOException {
        response.setContentType("application/json");
        response.setCharacterEncoding("utf-8");
        PrintWriter out = response.getWriter();
        String s = new ObjectMapper().writeValueAsString(resultVO);
        out.println(s);
        out.flush();
        out.close();
    }
    
}

 2.配置拦截器

@Configuration
public class InterceptorConfig implements WebMvcConfigurer {
    @Autowired
    private CheckTokenInterceptor checkTokenInterceptor;

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(checkTokenInterceptor)
                .addPathPatterns("/**")
                .excludePathPatterns("/user/**");
    }
}

 

   

标签:拦截器,springboot,54,resultVO,doResponse,response,token,new,ResultVO
来源: https://www.cnblogs.com/lysboke/p/16475170.html