当前位置: 首页> 文旅> 美景 > java:JWT的简单例子

java:JWT的简单例子

时间:2025/7/11 14:25:40来源:https://blog.csdn.net/chenhz2284/article/details/139885991 浏览次数:0次

【pom.xml】

<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId><version>2.3.12.RELEASE</version>
</dependency>
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-actuator</artifactId><version>2.3.12.RELEASE</version>
</dependency>
<dependency><groupId>com.auth0</groupId><artifactId>java-jwt</artifactId><version>3.19.1</version>
</dependency>

【JwtTest.java】

package com.chz.myJWT.utils;import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.HashMap;public class JwtTest {public static final String SECRET = "I_am_chz";public static String createJwtToken(){HashMap<String, Object> headers = new HashMap<>();Calendar expires = Calendar.getInstance();expires.add(Calendar.MINUTE, 30);       // 过期时间,60sString jwtToken = JWT.create()// 第一部分Header.withHeader(headers)// 第二部分Payload.withClaim("userId", 20).withClaim("userName", "chz").withExpiresAt(expires.getTime())// 第三部分Signature.sign(Algorithm.HMAC256(SECRET));return jwtToken;}public static DecodedJWT parseJwtToken(String jwtToken){JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(SECRET)).build();DecodedJWT decodedJWT = jwtVerifier.verify(jwtToken);return decodedJWT;}public static void main(String[] args){String jwtToken = createJwtToken();System.out.println("jwtToken: " + jwtToken);DecodedJWT decodedJWT = parseJwtToken(jwtToken);System.out.println("userId: " + decodedJWT.getClaim("userId").asInt());System.out.println("userName: " + decodedJWT.getClaim("userName").asString());System.out.println("expiresAt: " + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS").format(decodedJWT.getExpiresAt()));}
}

运行【JwtTest】
在这里插入图片描述

关键字:java:JWT的简单例子

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

责任编辑: