JWT令牌生成和验证的方法

JWT令牌生成和验证的方法

引入依赖:

<!-- https://mvnrepository.com/artifact/com.auth0/java-jwt -->
<dependency>
     <groupId>com.auth0</groupId>
     <artifactId>java-jwt</artifactId>
     <version>4.4.0</version>
</dependency>

添加测试方法:

package com.ztr.bigevent;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import org.junit.jupiter.api.Test;

import java.util.Date;
import java.util.HashMap;

public class JWTTest {

    // 生成token
    @Test
    public void test() {
        HashMap<String, Object> map = new HashMap<>();
        map.put("id",1);
        map.put("username","张三");
        String token = JWT.create().withClaim("user",map)  // 添加数据载荷
                .withExpiresAt(new Date(System.currentTimeMillis() + 1000 * 60 * 60 * 2))  // 添加过期时间
                .sign(Algorithm.HMAC256("ZOUTANGRUI")); // 配置密钥

        System.out.println(token);
    }

    // 验证Token
    @Test
    public void test01() {
        String token = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyIjp7ImlkIjoxLCJ1c2VybmFtZSI6IuW8oOS4iSJ9LCJleHAiOjE3MTcwNjI3NjN9.BASjtsmZh-KPsBOPgbav4OIvFoM6aHt95WQp4t6amO8";
        JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256("ZOUTANGRUI")).build();
        DecodedJWT verify = jwtVerifier.verify(token); // 验证token,生成解析后的jwt对象

        System.out.println(verify.getClaims().get("user"));
    }
}

  • 3
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值