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

import com.alibaba.fastjson.JSONObject;
import com.huaheng.common.utils.ServletUtils;
import com.huaheng.common.utils.StringUtils;
import com.huaheng.framework.redis.RedisCache;
import org.springframework.web.servlet.HandlerInterceptor;

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

        return true;
    }
}