山东大学软件工程项目实训_lwt(2021-4)(3)

山东大学软件工程项目实训(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 {}
}

未完待续 …

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值