旗开得胜

This commit is contained in:
2025-04-24 11:49:32 +08:00
parent ac5dd03c79
commit 2577c614d5
10 changed files with 362 additions and 10 deletions

View File

@ -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() {
}
}

View 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());
}
}