java:JWT的简单例子

【pom.xml】

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】

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);       // 过期时间,60s


        String 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】

相关推荐
海棠一号31 分钟前
JAVA理论第五章-JVM
java·开发语言·jvm
eternal__day1 小时前
Spring Cloud 多机部署与负载均衡实战详解
java·spring boot·后端·spring cloud·负载均衡
颜淡慕潇1 小时前
Redis 实现分布式锁:深入剖析与最佳实践(含Java实现)
java·redis·分布式
程序员秘密基地1 小时前
基于vscode,idea,java,html,css,vue,echart,maven,springboot,mysql数据库,在线考试系统
java·vue.js·spring boot·spring·web app
何中应1 小时前
【设计模式-5】设计模式的总结
java·后端·设计模式
吾日三省吾码1 小时前
Spring 团队详解:AOT 缓存实践、JSpecify 空指针安全与支持策略升级
java·spring·缓存
风象南2 小时前
SpringBoot的5种日志输出规范策略
java·spring boot·后端
咖啡啡不加糖2 小时前
深入理解MySQL死锁:从原理、案例到解决方案
java·数据库·mysql
zimoyin2 小时前
Compose Multiplatform 实现自定义的系统托盘,解决托盘乱码问题
java
啾啾Fun2 小时前
【Java微服务组件】分布式协调P4-一文打通Redisson:从API实战到分布式锁核心源码剖析
java·redis·分布式·微服务·lua·redisson