JWT(json web token) 工具类
json
适用于现代 C++ 的 JSON。
项目地址:https://gitcode.com/gh_mirrors/js/json
免费下载资源
·
问:什么是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>
GitHub 加速计划 / js / json
41.72 K
6.61 K
下载
适用于现代 C++ 的 JSON。
最近提交(Master分支:1 个月前 )
960b763e
3 个月前
8c391e04
6 个月前
更多推荐
已为社区贡献1条内容
所有评论(0)