ApiInterceptor.java 4.82 KB
package com.huaheng.framework.token;

import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.huaheng.common.exception.service.ServiceException;
import com.huaheng.common.utils.ServletUtils;
import com.huaheng.common.utils.StringUtils;
import com.huaheng.framework.redis.RedisCache;
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;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.security.SignatureException;

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

    @Resource
    private RedisCache redisCache;
    @Resource
    private IUserService userService;

    /**
     * 可以在这里设置各种规则,取到token后解析,来验证token有效性,有效期等等。这里仅仅验证了是不是token为空。
     */
    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {
        //这个就是从http头中取约定好的token的key。
        String token = httpServletRequest.getHeader("Authorization");
        Claims claims = null;
        try {
            if (token == null || "".equals(token.trim())) {
                throw new SignatureException("token is null");
            } else {
                token = token.substring(7);
                //token写入redis
                /*String user = redisCache.getCacheObject(token);
                if (StringUtils.isEmpty(user)) {
                    JSONObject jsonObject = new JSONObject();
                    jsonObject.put("msg", "token不正确或过期");
                    jsonObject.put("code", 401);
                    ServletUtils.renderString(httpServletResponse, jsonObject.toString());
                    return false;
                }*/
                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;
                }
            }
        } catch (SignatureException e) {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("msg", "请求参数中找不到Token");
            jsonObject.put("code", 401);
            ServletUtils.renderString(httpServletResponse, jsonObject.toString());
            return false;
        }
        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;
        }

        return true;
    }

    /**
     *
     * 解析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;
    }



}