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】

相关推荐
2301_7965125218 分钟前
Rust编程学习 - 如何利用代数类型系统做错误处理的另外一大好处是可组合性(composability)
java·学习·rust
清水39 分钟前
Spring Boot企业级开发入门
java·spring boot·后端
一个不称职的程序猿1 小时前
高并发场景下的缓存利器
java·缓存
2301_801252221 小时前
Tomcat的基本使用作用
java·tomcat
lkbhua莱克瓦241 小时前
Java基础——常用算法3
java·数据结构·笔记·算法·github·排序算法·学习方法
麦麦鸡腿堡1 小时前
Java_TreeSet与TreeMap源码解读
java·开发语言
教练、我想打篮球1 小时前
05 kafka 如何存储较大数据记录
java·kafka·record
uesowys2 小时前
华为OD算法开发指导-简易内存池
java·算法·华为od
gladiator+2 小时前
Java中的设计模式------策略设计模式
java·开发语言·设计模式
期待のcode2 小时前
Dockerfile镜像构建
java·docker·容器