JWT令牌

JWT令牌_第1张图片

引入maven依赖坐标 

                
        
            com.auth0
            java-jwt
            3.13.0
        
        
        
            org.springframework.boot
            spring-boot-starter-test
            3.1.2
        

JwtTest

package com.lin.springboot01;

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

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

public class JwtTest {
    @Test
    public void testGen(){
        Map claims = new HashMap<>();
        claims.put("id",1);
        claims.put("username","张三");
        //生成jwt的代码
        String token = JWT.create()
                .withClaim("user",claims)//添加载荷
                .withExpiresAt(new Date(System.currentTimeMillis()+1000*60/60*12))//添加过期时间
                .sign(Algorithm.HMAC256("lin2332"));//指定算法配置密钥
        System.out.println(token);

    }
}

密钥生成成功JWT令牌_第2张图片

校验密钥

package com.lin.springboot01;

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

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

public class JwtTest {
    @Test
    public void testGen(){
        Map claims = new HashMap<>();
        claims.put("id",1);
        claims.put("username","张三");
        //生成jwt的代码
        String token = JWT.create()
                .withClaim("user",claims)//添加载荷
                .withExpiresAt(new Date(System.currentTimeMillis()+1000*60*60*12))//添加过期时间
                .sign(Algorithm.HMAC256("lin2332"));//指定算法配置密钥
        System.out.println(token);
    }
    @Test
    public void testParse(){
        //定义字符串,模拟用户传递过来的token
        String token = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9" +
                ".eyJleHAiOjE2OTk3MTA5NDcsInVzZXIiOnsiaWQiOjEsInVzZXJuYW1lIjoi5byg5LiJIn19" +
                ".3CZM1OXRzVzRLCwfe5GrWIFcrJhy49XSjbQeIib-0SI";
        JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256("lin2332")).build();
        DecodedJWT decodedJWT = jwtVerifier.verify(token);
        Map claims = decodedJWT.getClaims();
        System.out.println(claims.get("user"));
    }
}

 jwt解析结果:JWT令牌_第3张图片JWT令牌_第4张图片

你可能感兴趣的:(springboot+vue,java,前端,linux)