JTW工具类

package com.neu.common.util;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.neu.common.dto.TokenResult;
import org.omg.CORBA.PRIVATE_MEMBER;

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

/**
 * Created with IntelliJ IDEA.
 *
 * @Author: yqq
 * @Date: 2023/03/26/21:16
 * @Description:
 */
public class JwtUtils {
    //盐
    private static final String SIGN = "NEUSOFT!#$$$";
    private static final String JWT_KEY_PHONE = "passengerPhone";
    //乘客是1 司机是2
    private static final String JWT_KEY_IDENTITY = "identity";
    //生成token
    public static String generatorToken(String passengerPhone,String identity){
        Map<String,String> map = new HashMap<>();
        map.put(JWT_KEY_PHONE,passengerPhone);
        map.put(JWT_KEY_IDENTITY,identity);
        //token过期时间
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.DATE,1);
        Date date = calendar.getTime();

        JWTCreator.Builder builder = JWT.create();
        //整合map
        map.forEach((k,v) -> {
            builder.withClaim(k,v);
        });
        //整合过期时间
        builder.withExpiresAt(date);
        //生成token
        String sign = builder.sign(Algorithm.HMAC256(SIGN));
        return sign;
    }

    //解析token
    public static TokenResult parseToken(String token){
        DecodedJWT verify = JWT.require(Algorithm.HMAC256(SIGN)).build().verify(token);
        String phone = verify.getClaim(JWT_KEY_PHONE).toString();
        String identity = verify.getClaim(JWT_KEY_IDENTITY).toString();
        TokenResult tokenResult = new TokenResult();
        tokenResult.setPhone(phone);
        tokenResult.setIdentity(identity);
        return tokenResult;
    }

    public static void main(String[] args) {
        String token = generatorToken("18224667883","1");
        System.out.println("生成的token:"+token);
        TokenResult tokenResult = parseToken(token);
        System.out.println("phone:"+tokenResult.getPhone());
        System.out.println("identity:"+tokenResult .getIdentity());
    }
}

生成的token:eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJwYXNzZW5nZXJQaG9uZSI6IjEwMDgwIiwiaWRlbnRpdHkiOiIxIiwiZXhwIjoxNjc5OTI4MjU0fQ.GOdApezZJKT8xF6GIXZT3QK-abSe8eoSq-0RjIHJwPw

phone:“10080”

identity:“1”

JWT生成token和解析token工具类_intellij-idea