平台鉴权处理

生成token和检验token

package com.demo.autotest.common.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.demo.autotest.database.domain.Demo;

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

public class JwtUtils {
    // 验签工具

    private static final String SECRET = "Test_Secret"; // 加密秘钥 动态生成secret

    private static final long EXPIRATION = 604800L; // 过期时间 7天

    public static String createToken(Demo demo) {
        // 生成token
        Date expireDate = new Date(System.currentTimeMillis() + EXPIRATION*1000); //过期时间
        Map<String, Object> map = new HashMap<>();
        map.put("alg", "HS256");
        map.put("typ", "JWT");
        String token = JWT.create()
                .withHeader(map)// 添加头部
                //可以将基本信息放到claims中
                .withClaim("id", demo.getId())//engineId
                .withClaim("name", demo.getName())//engineSecret
                .withExpiresAt(expireDate) //超时设置,设置过期的日期
                .withIssuedAt(new Date()) //签发时间
                .sign(Algorithm.HMAC256(SECRET)); //SECRET加密
        return token;
    }

    /**
     * 校验token并解析token
     */
    public static DecodedJWT verifyToken(String token) {
        DecodedJWT jwt = null;
        try {
            JWTVerifier verifier = JWT.require(Algorithm.HMAC256(SECRET)).build();
            jwt = verifier.verify(token);
        } catch (TokenExpiredException e) {
            // 时间校验出错抛出过期
            throw new TokenExpiredException("token已过期");
        }catch (Exception e) {
            // 解码异常抛出校验出错
            throw new JWTDecodeException("token校验出错");
        }
        // 返回基本信息
        return jwt;
    }

    public static void main(String[] args) {
        System.out.println(JwtUtils.createToken(new Demo()));
        
    }
}

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值