利用hutool生成和验证JWT的示例

利用hutool生成和验证JWT的示例

简介

利用hutool工具类生成json-web-token

  • hutool-all在5.7以上的版本才支持jwt

    <dependency>
        <groupId>cn.hutool</groupId>
        <artifactId>hutool-all</artifactId>
        <version>5.7.13</version>
    </dependency>
    

注意事项

  • key默认是按HS256(HmacSHA256)

  • 失效/生效时间校验

示例Code

JwtTest.java

package com.sedaier.calcdir.test;

import java.util.HashMap;
import java.util.Map;

import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DateTime;
import cn.hutool.jwt.JWTPayload;
import cn.hutool.jwt.JWTUtil;

public class JwtTest {

	public static void main(String[] args) {
		DateTime now = DateTime.now();
		DateTime newTime = now.offsetNew(DateField.MINUTE, 10);
		
		Map<String,Object> payload = new HashMap<String,Object>();
		//签发时间
		payload.put(JWTPayload.ISSUED_AT, now);
		//过期时间
		payload.put(JWTPayload.EXPIRES_AT, newTime);
		//生效时间
		payload.put(JWTPayload.NOT_BEFORE, now);
		//载荷
		payload.put("userName", "zhangsan");
		payload.put("passWord", "666889");
		
		String key = "aabb";
		String token = JWTUtil.createToken(payload, key.getBytes());
		System.out.println(token);
	}

}

JwtVerify.java

package com.sedaier.calcdir.test;

import cn.hutool.jwt.JWT;
import cn.hutool.jwt.JWTUtil;

public class JwtVerify {

	public static void main(String[] args) {
		String key = "aabb";
		String token = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJwYXNzV29yZCI6IjY2Njg4OSIsIm5iZiI6MTYzNTE1MDI3NiwiZXhwIjoxNjM1MTUwODc2LCJ1c2VyTmFtZSI6InpoYW5nc2FuIiwiaWF0IjoxNjM1MTUwMjc2fQ.Cq2AHyrZ-Q7U7O5BBPdEIBrm7aDtjQh4ZDvtIcLzQvg";
		JWT jwt = JWTUtil.parseToken(token);
		
		boolean verifyKey = jwt.setKey(key.getBytes()).verify();
		System.out.println(verifyKey);
		
		boolean verifyTime = jwt.validate(0);
		System.out.println(verifyTime);
	}

}

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/qq125281823/article/details/120960181