严智鑫
2024-04-19 04b841aa1661693e68f5dea1a80e7c97a209cbeb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
package com.mes.common.interceptor;
 
import cn.hutool.core.util.StrUtil;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.mes.common.CacheUtil;
import com.mes.common.Constants;
import com.mes.controller.dto.UserDTO;
import com.mes.exception.ServiceException;
import com.mes.service.userInfo.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
 
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
 
@Component
public class JwtInterceptor implements HandlerInterceptor {
 
    @Autowired
    private UserService userService;
    @Autowired
    private CacheUtil cacheUtil;
 
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //return HandlerInterceptor.super.preHandle(request, response, handler);
        /*String token=request.getHeader("token");
        if(!(handler instanceof HandlerMethod)){
            return  true;
        }
 
        if(StrUtil.isBlank(token)){
            throw new ServiceException(Constants.Code_401,"无token,重新登陆");
        }
        String userId;
        try{
            userId = JWT.decode(token).getAudience().get(0);
        }catch (Exception e){
            throw new ServiceException(Constants.Code_500,"token格式错误");
        }
 
        UserDTO getUserDTO = cacheUtil.getCacheData(userId);
 
        if(getUserDTO != null && !getUserDTO.getToken().equals(token)){
            throw new ServiceException(Constants.Code_600,"用户在其他位置登陆");
        }
 
 
        String password=userService.getUserByID(userId).toLowerCase();
        //用户密码加签验证
        JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(password)).build();
        try {
            jwtVerifier.verify(token);
        } catch (JWTVerificationException e) {
            throw new ServiceException(Constants.Code_401,"token验证失败,请重新登陆");
        }*/
        return true;
    }
 
}