旗开得胜
This commit is contained in:
@ -1,13 +1,20 @@
|
||||
package com.greenorange.promotion;
|
||||
|
||||
import com.auth0.jwt.JWT;
|
||||
import com.auth0.jwt.algorithms.Algorithm;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
|
||||
import java.util.Calendar;
|
||||
import java.util.HashMap;
|
||||
|
||||
@SpringBootTest
|
||||
class GreenOrangeApplicationTests {
|
||||
|
||||
@Test
|
||||
void contextLoads() {
|
||||
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
47
src/test/java/com/greenorange/promotion/JwtDemo.java
Normal file
47
src/test/java/com/greenorange/promotion/JwtDemo.java
Normal file
@ -0,0 +1,47 @@
|
||||
package com.greenorange.promotion;
|
||||
|
||||
import com.auth0.jwt.JWT;
|
||||
import com.auth0.jwt.algorithms.Algorithm;
|
||||
import com.auth0.jwt.interfaces.DecodedJWT;
|
||||
|
||||
import com.auth0.jwt.interfaces.JWTVerifier;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.Calendar;
|
||||
import java.util.HashMap;
|
||||
|
||||
public class JwtDemo {
|
||||
|
||||
@Test
|
||||
public void test() {
|
||||
|
||||
HashMap<String, Object> map = new HashMap<>();
|
||||
|
||||
Calendar instance = Calendar.getInstance();
|
||||
// 20秒后令牌token失效
|
||||
instance.add(Calendar.HOUR,1);
|
||||
|
||||
String token = JWT.create()
|
||||
.withHeader(map) // header可以不写,因为默认值就是它
|
||||
.withClaim("userId", 21) //payload
|
||||
.withClaim("username", "xiaoshuang")
|
||||
.withExpiresAt(instance.getTime()) // 指定令牌的过期时间
|
||||
.sign(Algorithm.HMAC256("XIAOSHUANG"));//签名
|
||||
|
||||
System.out.println(token);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testVerifier(){
|
||||
// 通过签名生成验证对象
|
||||
JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256("XIAOSHUANG")).build();
|
||||
|
||||
DecodedJWT verify = jwtVerifier.verify("eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJleHAiOjE3NDU0NjE4NDYsInVzZXJJZCI6MjEsInVzZXJuYW1lIjoieGlhb3NodWFuZyJ9.oN1KdeASH4yqjJBn4hb9jux_VWXWXRz9DSE81RML9Ak");
|
||||
System.out.println(verify.getClaim("userId"));
|
||||
System.out.println(verify.getClaim("username"));
|
||||
System.out.println("令牌过期时间:"+verify.getExpiresAt());
|
||||
|
||||
}
|
||||
|
||||
|
||||
}
|
Reference in New Issue
Block a user