ApiInterceptor.java
2.02 KB
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
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;
}
}