山东大学软件工程项目实训(2021-4)
实现过滤器,联系前端进行调试
一、本阶段工作进展
1.修改token工具类
加入快过期更新
抛弃状态,直接抛出错误
// 判断 token 是否 有效0/快过期1/过期2/无效3
public static String checkToken(String token) {
String result;
// 判null
if (token == null) {
throw new RuntimeException("500 (Error: token is null in checkToken)");
}
// 获取 token 中的信息 ( id ExpireTime )
String content;
try {
content = JWT.decode(token).getAudience().get(0);
} catch (JWTDecodeException j) {
throw new RuntimeException("500 (jwt decode error)");
}
String secret = secretKey + content.split(";;")[0];
// 验证 token
JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(secret)).build();
try {
jwtVerifier.verify(token);
} catch (JWTVerificationException e) {
throw new RuntimeException("500 (jwt verify error)");
}
// 查看 token 的 有效期
long expireTime = Long.parseLong(content.split(";;")[1]);
long currentTime = System.currentTimeMillis();
// 已过期
if (currentTime > expireTime){
throw new RuntimeException("500 (token expire)");
}else {
// 快过期
if (expireTime - currentTime < tokenNearExpireTime){
long newExpireTime = System.currentTimeMillis() + tokenExpireTime*60*1000L;
String newToken= JWT.create().withAudience(content.split(";;")[0] +";;"+ newExpireTime)
.sign(Algorithm.HMAC256(secret));
result = newToken;
}else {
// 正常有效
result = token;
}
}
return result;
}
原修改类
// public static Map<String,String> checkToken(String token) {
// Map<String, String> res = new HashMap<String, String>();
// // 判null
// if (token == null) {
// res.put("state","invalid");
// res.put("token",null);
// throw new RuntimeException("Error: token is null in checkToken ");
// }
// // 获取 token 中的信息 ( id ExpireTime )
// String content;
// try {
// content = JWT.decode(token).getAudience().get(0);
// } catch (JWTDecodeException j) {
// res.put("state","invalid");
// res.put("token",null);
// throw new RuntimeException("401 (jwt decode error)");
// }
// String secret = secretKey + content.split(";;")[0];
// // 验证 token 如果验证失败应该返回FALSE???
// JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(secret)).build();
// try {
// jwtVerifier.verify(token);
// } catch (JWTVerificationException e) {
// res.put("state","invalid");
// res.put("token",null);
// throw new RuntimeException("401 (jwt verify error)");
// }
// // 验证成功
// // 查看 token 的 有效期
// long expireTime = Long.parseLong(content.split(";;")[1]);
// long currentTime = System.currentTimeMillis();
// // 已过期
// if (currentTime > expireTime){
// res.put("state","expire");
// res.put("token",null);
// }else {
// // 快过期
// if (expireTime - currentTime < 5*60*1000){
// res.put("state","invalid");
// long newExpireTime = System.currentTimeMillis() + tokenExpireTime*60*1000L;
// String newToken= JWT.create().withAudience(content.split(";;")[0] +";;"+ newExpireTime)
// .sign(Algorithm.HMAC256(secret));
// res.put("token",newToken);
// }else {
// // 正常有效
// res.put("state","valid");
// res.put("token",token);
// }
// }
// // 有效
// return res;
// }
进行测试
/** test checkToken() **/
String res = checkToken(token);
System.out.println("|--有效: \t\t\t"+res);
System.out.println("|------");
TimeUnit.MINUTES.sleep(2);//分
res = checkToken(token);
System.out.println("|--快过期: \t\t\t"+res);
System.out.println("|------");
TimeUnit.MINUTES.sleep(2);//分
res = checkToken(token);
System.out.println("|--过期: \t\t\t"+res);
System.out.println("|------");
测试结果
2.编写过滤器
@Component
@WebFilter(urlPatterns = { "/*" }, filterName = "tokenAuthorFilter")
public class TokenAuthorFilter implements Filter {
private static Logger logger = LoggerFactory.getLogger(TokenAuthorFilter.class);
@Resource
private UserMapper userMapper;
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
HttpServletRequest req = (HttpServletRequest) request;
String token = req.getHeader("token");
logger.info("token:{}", token);
if (null == token || token.isEmpty()) {
throw new ServletException("用户授权认证没有通过...客户端请求参数中无token信息");
} else {
if (this.volidateToken(token)) {
//通过校验
logger.info("token过滤完成");
chain.doFilter(request, response);
} else {
throw new ServletException("用户授权认证没有通过...客户端请求参数token信息无效");
}
}
}
public boolean volidateToken(String token) {
return token.equals(TokenUtil.checkToken(token));
}
@Override
public void destroy() {}
@Override
public void init(FilterConfig filterConfig) throws ServletException {}
}
未完待续 …