Blame view

src/main/java/com/huaheng/framework/token/ApiInterceptor.java 4.82 KB
mahuandong authored
1
2
3
package com.huaheng.framework.token;

import com.alibaba.fastjson.JSONObject;
4
5
import com.fasterxml.jackson.databind.ObjectMapper;
import com.huaheng.common.exception.service.ServiceException;
mahuandong authored
6
7
8
import com.huaheng.common.utils.ServletUtils;
import com.huaheng.common.utils.StringUtils;
import com.huaheng.framework.redis.RedisCache;
9
10
11
12
13
14
15
import com.huaheng.framework.web.domain.AjaxResult;
import com.huaheng.pc.system.user.domain.User;
import com.huaheng.pc.system.user.service.IUserService;
import com.lowagie.text.pdf.codec.Base64;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.Jwts;
mahuandong authored
16
17
18
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
19
20
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
mahuandong authored
21
22
23
24
25
26
27
28
29
30
31
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.security.SignatureException;

/**
 * Created by Enzo Cotter on 2020/6/11.
 */
public class ApiInterceptor implements HandlerInterceptor {

    @Resource
    private RedisCache redisCache;
32
33
34
35
36
    @Resource
    private IUserService userService;
mahuandong authored
37
38
39
40
41
42
43
    /**
     * 可以在这里设置各种规则,取到token后解析,来验证token有效性,有效期等等。这里仅仅验证了是不是token为空。
     */
    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {
        //这个就是从http头中取约定好的token的key。
        String token = httpServletRequest.getHeader("Authorization");
44
        Claims claims = null;
mahuandong authored
45
46
47
48
49
        try {
            if (token == null || token.trim().equals("")) {
                throw new SignatureException("token is null");
            } else {
                token = token.substring(7);
50
51
                //token写入redis
                /*String user = redisCache.getCacheObject(token);
mahuandong authored
52
53
54
55
56
57
                if (StringUtils.isEmpty(user)) {
                    JSONObject jsonObject = new JSONObject();
                    jsonObject.put("msg", "token不正确或过期");
                    jsonObject.put("code", 401);
                    ServletUtils.renderString(httpServletResponse, jsonObject.toString());
                    return false;
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
                }*/
                JSONObject jsonObject = new JSONObject();
                try {
                    claims = this.parseJWT(token);
                } catch (ExpiredJwtException e) {
                    jsonObject.put("code", 401);
                    ServletUtils.renderString(httpServletResponse, jsonObject.toString());
                    return false;
                } catch (SignatureException e) {
                    jsonObject.put("code", 401);
                    ServletUtils.renderString(httpServletResponse, jsonObject.toString());
                    return false;
                } catch (Exception e) {
                    jsonObject.put("code", 401);
                    ServletUtils.renderString(httpServletResponse, jsonObject.toString());
                    return false;
mahuandong authored
74
75
76
77
78
79
80
81
82
                }
            }
        } catch (SignatureException e) {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("msg", "请求参数中找不到Token");
            jsonObject.put("code", 401);
            ServletUtils.renderString(httpServletResponse, jsonObject.toString());
            return false;
        }
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
        User user = new User();
        //token解析数据 ,
        try{
            Object userTmp = claims.get("user",Object.class);
            //object转对象
            ObjectMapper objectMapper = new ObjectMapper();
            user = objectMapper.convertValue(userTmp,User.class);
        }catch (Exception e){
            throw new ServiceException(e.toString());
        }
        if(StringUtils.isEmpty(user.getLoginName()) || StringUtils.isEmpty(user.getPassword()) || StringUtils.isEmpty(user.getWarehouseCode())){
            throw new ServiceException("写入session必要字段错误!");
        }
        //session登录
        AjaxResult ajaxResult = userService.login(user.getLoginName(), user.getPassword(), user.getWarehouseCode(), false);
        if(ajaxResult.getCode() != 200){
            return false;
        }
mahuandong authored
101
102
103

        return true;
    }
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128

    /**
     *
     * 解析JWT字符串
     * @param jwt
     * @return
     * @throws Exception
     */
    public Claims parseJWT(String jwt) throws Exception {
        SecretKey secretKey = this.generalKey();
        Claims k = Jwts.parser()
                .setSigningKey(secretKey)
                .parseClaimsJws(jwt)
                .getBody();
        return k;
    }

    public SecretKey generalKey() {
        byte[] encodedKey = Base64.decode(TokenService.signingKey);
        SecretKey key = new SecretKeySpec(encodedKey, 0, encodedKey.length, "AES");
        return key;
    }
mahuandong authored
129
}