入门学习JWT(代码测试)

什么是JWT:

1. JSON Web Token ====》JWT
2. jwt是信息加密的一种方式,一个JWT由三个部分组成:header,payload,signature。分别保存了不同的信息。三个部分在JWT中分别对应英文句号分割出来的三个串
3. payload中通常base64加密,可以被反编译,所以敏感信息尽量不要放到里面

pom.xml导入mvn依赖:

 <dependency>
            <groupId>com.auth0</groupId>
            <artifactId>java-jwt</artifactId>
            <version>3.13.0</version>
        </dependency>

applicationTests:

package com.example.smdemo;

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 org.springframework.boot.test.context.SpringBootTest;

import java.util.Calendar;
import java.util.HashMap;

@SpringBootTest
class SmdemoApplicationTests {

    @Test
    void contextLoads() {
        HashMap<String,Object> map = new HashMap<>();
        Calendar instance = Calendar.getInstance();
        instance.add(Calendar.SECOND,600);

        String token = JWT.create().
                withHeader(map).                  //header
                withClaim("userId",12).           //payload
                withClaim("userName","张三").     //payload
                withExpiresAt(instance.getTime()).                         //指定令牌过期时间
                sign(Algorithm.HMAC256("#AWMAKM4"));             //签名

        System.out.println(token);
    }
    @Test
    public void test(){
        //创建验证对象
        JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256("#AWMAKM4")).build();
        DecodedJWT verify = jwtVerifier.verify("eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyTmFtZSI6IuW8oOS4iSIsImV4cCI6MTYxNjQ4MzQyMywidXNlcklkIjoxMn0.vRSbeoupquBUDGeQHhltPUgk5CIQQr7fMAALjmFAIPM");

        System.out.println("用户id:"+verify.getClaim("userId").asInt());
        System.out.println("用户名:"+verify.getClaim("userName").asString());
        System.out.println("过期时间:"+verify.getExpiresAt());

    }

}

打印结果:

用户id:12
用户名:张三
过期时间:Tue Mar 23 15:10:23 CST 2021

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值