JWT工具类

JWT技术通常用来做微服务无状态验证,简介便用,不占用服务器内存空间。
废话不多说,工具类如下,直接拿去用

package com.demo.util;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.SignatureVerificationException;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.auth0.jwt.interfaces.DecodedJWT;

import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

/**
 * @Author lf
 * @Date 2021-5-13 7:36
 */
public class JwtUtil {


    public static String createToken(Map<String,String> payload){
        JWTCreator.Builder builder = JWT.create();
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.MINUTE,30);//超时时间30分钟
        Set<Map.Entry<String, String>> entries = payload.entrySet();
        //设置负载
        for (Map.Entry<String, String> entry: entries) {
            builder.withClaim(entry.getKey(),entry.getValue());
        }
        String token = builder
                .withExpiresAt(calendar.getTime())//过期时间
                .sign(Algorithm.HMAC256("pro2021"));//签名加盐

        return token;
    }

    //校验
    public static DecodedJWT verify(String token) throws Exception{
        JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256("pro2021")).build();
        DecodedJWT verify = jwtVerifier.verify(token);
        return verify;
    }


    public boolean checkToken(String token){
        try {
            verify(token);
            return true;
        }catch (SignatureVerificationException e){
            //这里可以用slf4j做日志
            System.out.println("签名不一致异常"+e);
        }catch (TokenExpiredException e){
            System.out.println("令牌过期异常"+e);
        }catch (Exception e){
            System.out.println("token认证失败");
        }
        return false;
    }

    public static String getWitchClaim(String token,String key){
        try {
            DecodedJWT verify = verify(token);
            return verify.getClaim(key).asString();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }


    public static void main(String[] args) {
        /*HashMap<String, String> map = new HashMap<>();
        map.put("name","张三");
        String token = createToken(map);
        System.out.println(token);*/


        String name = getWitchClaim("eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJuYW1lIjoi5byg5LiJIiwiZXhwIjoxNjIwODY2Mjg0fQ.ruiW7eTAA1LUUsaozm5OUF75DPLCmACKWU5-cxTDkRA", "name");
        System.out.println(name);

    }

}


-END-

如果你喜欢我的分享,欢迎关注微信公众号 java学长分享技术干货!

悄悄告诉你免费赠送重磅互联网架构师教程,提升职场技术水平!

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

IT悍将阿瑞

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值