JWT(json web token) 工具类

问:什么是jwt?


答:

请跳转:

http://lion1ou.win/2017/01/18/?hmsr=toutiao.io&utm_medium=toutiao.io&utm_source=toutiao.io&nsukey=Y4xKsWO39E4HeE1bH0Xfr6i0wQITKfoKOGI4r7gA9MRdfYDie2FtBco71Ld4vawCEkbdSzZ1A85LBfGygTCJxSfNtis14l4L0km2SVYeQagyD8fHTH2BoINnRkNVCQMqzax52PbXqmA6LQZ8DS7cnrIpdOZJJaccj4GmJInF0e2B8jhSwyA26xayIRKWpdbn0RoBNoarLQvXcIuL69vBp92BrA3D3D




工具类:

package com.zzkx.udp.framework.jwt;

import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;

public class JwtTokenUtil {

	public static String SECRET = "SDFEEdfdeFDRE";
	
	
	public static String createToken() throws Exception {
		//签发时间
		Date istDate = new Date();
		
		//设置过期时间
		Calendar nowTime = Calendar.getInstance();
		nowTime.add(Calendar.MINUTE, 1);
		Date expiresDate = nowTime.getTime();
		
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("alg", "HS256");
		map.put("typ", "JWT");
		
		String token = JWT.create()
				.withHeader(map)
				.withClaim("name", "test")
				.withClaim("age", 11)
				.withExpiresAt(expiresDate)
				.withIssuedAt(istDate)
				.sign(Algorithm.HMAC256(SECRET));
		
		return token;
	}
	
	
	public static Map<String, Claim> verifyToken(String token) throws Exception{
		JWTVerifier verifier = JWT.require(Algorithm.HMAC256(SECRET)).build();
		DecodedJWT jwt = null;
		try {
			jwt = verifier.verify(token);
		} catch (Exception e) {
			throw new RuntimeException("凭证过期!");
		}
		
		return jwt.getClaims();
	}
	
	
	
	public static void main(String[] args) throws Exception {
		String token = JwtTokenUtil.createToken();
		
		System.out.println(token);
		//正常测试
		Map<String, Claim> verifyToken = JwtTokenUtil.verifyToken(token);
		String asString = verifyToken.get("name").asString();
		System.out.println(asString);
		
		//过期测试
		token = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJuYW1lIjoidGVzdCIsImV4cCI6MTUyNzQ5NzA3MiwiaWF0IjoxNTI3NDk3MDExLCJhZ2UiOjExfQ.yg1Hn4FT0OWu8KecNzvaayMEbbDrKctjWlI4bblcRfA";
		Map<String, Claim> verifyToken2 = JwtTokenUtil.verifyToken(token);
	}
}


maven:

        <dependency>
		    <groupId>com.auth0</groupId>
		    <artifactId>java-jwt</artifactId>
		    <version>3.2.0</version>
		</dependency>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值