本文来说下JWT的实战部分
概述
前面说了很多JWT的理论知识,本文先来说下在java环境中如何使用JWT。
maven导入
<!-- https://mvnrepository.com/artifact/com.auth0/java-jwt -->
<dependency>
<groupId>com.auth0</groupId>
<artifactId>java-jwt</artifactId>
<version>3.4.0</version>
</dependency>
代码实战
生成token
package cn.wideth.jwt;
import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import org.junit.Test;
import java.util.Calendar;
import java.util.HashMap;
public class JwtTest {
/***
* 获得一个
* token
*/
@Test
public void getToken(){
HashMap<String,Object> map = new HashMap<>();
Calendar instance = Calendar.getInstance();
instance.add(Calendar.SECOND,100);
String token = JWT.create()
.withHeader(map)//header
.withClaim("userId","20")//payload
.withClaim("username","xiaoming")
.withExpiresAt(instance.getTime())//指定令牌过期时间
.sign(Algorithm.HMAC256(("@2WwSsXx")));//签名
System.out.println(token);
}
}
程序结果
token是一个长字符串,如下所示
eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJleHAiOjE2MjQ3OTY5OTgsInVzZXJJZCI6IjIwI
iwidXNlcm5hbWUiOiJ4aWFvbWluZyJ9.tlbj6rMHBpY4il9Jk55B18MtgEjQ9Oc1UvfLG3oTkK4
根据令牌和签名解析数据
/***
* 根据token和令
* 牌解析用户数据
*/
@Test
public void getUserInfo(){
JWTVerifier jWTVerifier = JWT.require(Algorithm.HMAC256("@2WwSsXx")).build();
DecodedJWT verify = jWTVerifier.verify("eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJleHAiOjE2MjQ3OTgyNDMsInVzZXJJZCI6IjIwIiwidXNlcm5hbWUiOiJ4aWFvbWluZyJ9.7W1_zEoLHp4kJB3tgx0yArAjfok1_qXT7OYWciH64B8\n");
System.out.println(verify.getClaims().get("userId").asString());
System.out.println(verify.getClaims().get("username").asString());
}
程序结果
JWT工具类
package cn.wideth.jwt;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;
/**
* jwt的一个
* 简单工具类
*/
public class JwtUtil {
private static final String SING = "ABCD1234#$%^&";
public static String getToken(Map<String,String> map){
Calendar instance = Calendar.getInstance();
instance.add(Calendar.DATE,7);//默认7天过期
//创建jwt builder
JWTCreator.Builder builder = JWT.create();
//payload
map.forEach((k,v)->{
builder.withClaim(k,v);
});
String token = builder.withExpiresAt(instance.getTime()).//指定过期时间
sign(Algorithm.HMAC256(SING));//sign
return token;
}
/***
* 验证token
* 的合法性
* @param token
* @return
*/
public static DecodedJWT verify(String token){
return JWT.require(Algorithm.HMAC256(SING)).build().verify(token);
}
/**
* 使用main函
* 数来进行测试
* @param args
*/
public static void main(String[] args) {
Map<String,String> map = new HashMap<>();
map.put("userId","100");
map.put("username","hello");
String token = getToken(map);
System.out.println(token);
DecodedJWT verify = verify(token);
System.out.println(verify.getClaims().get("userId").asString());
System.out.println(verify.getClaims().get("username").asString());
}
}
程序结果