程序员的资源宝库

网站首页 > gitee 正文

Java hutool.jwt

sanyeah 2024-04-12 17:38:22 gitee 7 ℃ 0 评论

import cn.hutool.jwt.JWT;
import cn.hutool.jwt.JWTUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.map.HashedMap;

import java.util.Date;
import java.util.Map;

@Slf4j
public class Jwt {
    public static void main(String[] args) {
        //make();
        parse();
    }

    private static void make() {
        Date now = new Date();

        Map<String, Object> map = new HashedMap();
        map.put("username", "aaa");
        map.put("password", "bbb");
        map.put("time", now.getTime());

        byte[] bytes = "token".getBytes();

        String jwt = JWTUtil.createToken(map, bytes);
        log.info(jwt);
    }

    private static void parse() {
        Date now = new Date();
        log.info("{} = {}", now.getTime(), now);

        byte[] bytes = "token".getBytes();
        String s = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJwYXNzd29yZCI6ImJiYiIsInRpbWUiOjE3MDQ3ODc5OTYzNDMsInVzZXJuYW1lIjoiYWFhIn0.sXmNXq3jLClqYjvsIEwuWWUaMQ2ruV7-e02rJDRYAbA";
        boolean b = JWTUtil.verify(s, bytes);
        if (b) {
            JWT jwt = JWTUtil.parseToken(s);
            log.info("{}", jwt.getPayloads());

            Long l = (long) jwt.getPayload("time");
            Date then = new Date(l);
            log.info("{} = {}", l, then);

            long sec = (now.getTime() - l)/1000;
            log.info("takes {} s", sec);
            if (sec > 60) {
                log.info("over");
            }

        }
    }
}

附hutool相关pom:

<!-- hutool https://www.hutool.cn/docs/#/ -->
        <dependency>
            <groupId>cn.hutool</groupId>
            <artifactId>hutool-all</artifactId>
            <version>5.8.5</version>
        </dependency>

 

Tags:

本文暂时没有评论,来添加一个吧(●'◡'●)

欢迎 发表评论:

最近发表
标签列表