auth0 封装 JwtUtils

1.引入依赖

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

2.jwt工具类

package com.wsz.security.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import org.springframework.stereotype.Component;

import javax.crypto.spec.SecretKeySpec;
import java.util.*;

@Component
public class JwtUtils {
    private static final Long JWTREF_TTL = 60 * 60 * 1000L * 24 * 14;//refresh令牌的刷新事件为14day
    private static final Long JWTACS_TTL = 60 * 60 * 1000L * 2;//权限信息token有效时间为2h

    public static final String JWT_KEY = "XXXXXXXXXXXX46位密钥XXXXXXXXXXX";

    public static String getUUID() {
        return UUID.randomUUID().toString().replaceAll("-", "");
    }//通过uuid动态生成

    public static String createRefreshToken(String username,String uri) {
        Long time = System.currentTimeMillis();
        return   JWT.create()
                .withSubject(username)
                .withIssuedAt(new Date(time))
                .withExpiresAt(new Date(time + JWTREF_TTL))
                .withIssuer("wsz:"+uri)
                .sign(generalKey());
    }

    public static String createAccessToken(String username, String uri, List<String> roles) {
        Long time = System.currentTimeMillis();
        return   JWT.create()
                .withSubject(username)//主题
                .withIssuedAt(new Date(time))   //生成时间
                .withExpiresAt(new Date(time + JWTACS_TTL))//过期事件
                .withIssuer("wsz:"+uri)   //token发布者和其调用地址
                .withClaim("roles",roles)//给PAYLOAD添加一跳数据 => 自定义声明 (key,value)
                .sign(generalKey());
    }

    public static Algorithm generalKey() {
        byte[] encodeKey = Base64.getDecoder().decode(JwtUtils.JWT_KEY);//使用 Base64 编码方案解码输入字节数组/字符串/字节缓冲中的所有字节, 将结果写入新分配的输出字节数组/字节缓冲中.
        String key1 = new SecretKeySpec(encodeKey, 0, encodeKey.length, "HmacSHA256").toString();//将其字节数字组按给定算法加密
        return Algorithm.HMAC256(key1);
    }

    public static DecodedJWT parseToken(String jwt) {
        return  JWT.require(generalKey()).build().verify(jwt);
    }

}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值