码迷,mamicode.com
首页 > 其他好文 > 详细

jwt基本使用

时间:2021-01-27 13:16:42      阅读:0      评论:0      收藏:0      [点我收藏+]

标签:mac   instance   验证   algorithm   bsp   pre   auth   expires   hmac   

1、JWT依赖

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

2、写个测试类测试下JWT

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.Calendar;
import java.util.HashMap;

public class JwtText {
    @Test
   void jwttext(){
       HashMap<String,Object> map=new HashMap<>();
       Calendar instance=Calendar.getInstance();
       instance.add(Calendar.SECOND,300);

       String token= JWT.create()
               .withClaim("userid",21)
               .withClaim("username","iJun")
               .withExpiresAt(instance.getTime())
               .sign(Algorithm.HMAC256("学习java..."));
       System.out.println(token);
   }
   @Test
   void Yantext(){
       //验证对象
        JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256("学习java...")).build();
       DecodedJWT verify = jwtVerifier.verify("eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJleHAiOjE2MTE1MDMzNjAsInVzZXJpZCI6MjEsInVzZXJuYW1lIjoiaUp1biJ9.Lw6oENQq7gXv1U_USMjj2zG_Z5Zhkd7CfKk7L4czXbo");
       System.out.println(verify.getClaim("userid").asInt());
       System.out.println(verify.getClaim("username").asString());
       System.out.println(verify.getExpiresAt());
   }
}

 

jwt基本使用

标签:mac   instance   验证   algorithm   bsp   pre   auth   expires   hmac   

原文地址:https://www.cnblogs.com/JunHello/p/14328168.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!