JWT-JAVA简单测试用例

 

 

package com.ht.web.util;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTCreationException;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.interfaces.DecodedJWT;

import java.util.Date;

public class JwtDemo {

    public static void main(String[] main) {
        try {
            //创建加密算法
            Algorithm algorithm = Algorithm.HMAC256("secret");
            String token = JWT.create()
                    //签发者
                    .withIssuer("auth0")
                    //自定义KV
                    .withClaim("admin", "jack")
                    //过期时间,必须大于签发时间
                    .withExpiresAt(new Date())
                    //生效时间,定义在什么时间之前,该Token都是不可用的
                    .withNotBefore(new Date())
                    //签发时间,一般为当前时间
                    .withIssuedAt(new Date())
                    .sign(algorithm);
            System.out.println(token);
        } catch (JWTCreationException exception){
            //Invalid Signing configuration / Couldn't convert Claims.
        }

        String token = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJhdXRoMCIsImFkbWluIjoiamFjayIsImlhdCI6MTU4MzkxMjIxOH0.8aTS51RiyNs9lEjLDvSr7SHb_ON2x6E4zeJGWAo_IsI";
        try {
            //创建加密算法
            Algorithm algorithm = Algorithm.HMAC256("secret");
            JWTVerifier verifier = JWT.require(algorithm)
              //可以强制判断token当中是否包含此字段
                    .withIssuer("auth0")
                    .withClaim("admin", "jack")
                    //单位秒: 可以接受过期的时间长度,
                    //比如过期时间为15:30:00,可以往后延45秒,那么过期时间为15:30:45
                    .acceptExpiresAt(45)

                    //单位秒:可以接受提前使用的时间长度,
                    //比如NotBefore定以为15:30:00,那么在到时间之前正常token都不可用
                    //设置为60,代表提前一分钟可以用  那么token在15:29:00就可以用了
                    .acceptNotBefore(60)
                    .build();
            DecodedJWT jwt = verifier.verify(token);
            System.out.println(jwt.getClaim("admin").asString());
            System.out.println(jwt.getExpiresAt());
            System.out.println(jwt.getIssuedAt());
        } catch (JWTVerificationException exception){
            //Invalid signature/claims
            exception.printStackTrace();
        }
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值