jwt token

package com.example.demo.test.token;

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

import com.alibaba.fastjson.JSON;
import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.auth0.jwt.interfaces.JWTVerifier;

public class JwtToken {

    // 过期时间
    private static final long EXPIRE_TIME = 15 * 60 * 1000; // 15min
    // 私钥
    private static final String TOKEN_SECRET = "privateKey";

//    public static final String TOKEN_AES_KEY = "xiangli8Token";
//    public static final String REFREH_TOKEN_AES_KEY = "xiangli8RefreshToken";
//    public static final String JWT_TYP = "JWT";
//    public static final String JWT_ALG = "AES";
//    public static final String JWT_EXP = "30";
//    public static final String JWT_ISS = "xiangli8";

    public static String createToken(String userId, String pwd) {

//        String token= JWT.create().withAudience("audience")
//                   .withIssuedAt(new Date())
//                   .withSubject("subject")
//                   .withExpiresAt(new Date()).withJWTId("jtiid")
//                   .sign(Algorithm.HMAC256("123456"));

        try {
            long nowTime = System.currentTimeMillis();
            // 设置签发时间
            Date nowDate = new Date(nowTime);
            // 设置过期时间
            Date ExpiresDate = new Date(nowTime + EXPIRE_TIME);
            // 私钥和加密算法
            Algorithm algorithm = Algorithm.HMAC256(TOKEN_SECRET);
            // 设置头部信息
            Map<String, Object> header = new HashMap<>(2);
            header.put("Type", "Jwt");
            header.put("alg", "HS256");
            // 返回token字符串
            return JWT.create().withHeader(header).withClaim("userId", userId).withClaim("pwd", pwd)
                    .withIssuedAt(nowDate).withExpiresAt(ExpiresDate).sign(algorithm);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }

    }

    /**
     * token解密jwt
     * 
     * @param token
     * @return
     * @throws Exception
     */
    public static DecodedJWT getJWT(String token) {
        try {
            Algorithm algorithm = Algorithm.HMAC256(TOKEN_SECRET);
            JWTVerifier verifier = JWT.require(algorithm).build();
            DecodedJWT jwt = verifier.verify(token);
            return jwt;
        } catch (Exception e) {
        }
        return null;
    }

    /**
     * 检验token是否正确
     * 
     * @param **token**
     * @return
     */
    public static boolean verify(String token) {
        DecodedJWT jwt = getJWT(token);
//            String userId = jwt.getClaim("userId").asString();
        if (null != jwt) {
            return true;
        }
        return false;
    }

}
 

 

 

测试

 

    public static void main(String[] args) {
        // TODO Auto-generated method stub

        String token = JwtToken.createToken("zhangsan", "1234qwer");

        System.out.println("token:" + token);
        token="eyJUeXBlIjoiSnd0IiwidHlwIjoiSldUIiwiYWxnIjoiSFMyNTYifQ.eyJwd2QiOiIxMjM0cXdlciIsImV4cCI6MTU5MDQ1ODA4NiwidXNlcklkIjoiemhhbmdoYW8iLCJpYXQiOjE1OTA0NTcxODZ9.cVcq-FTCqhESpIy3_vvJJzPrGy-ZEy4lGKnQxLMjsgY" + 
                "";
        boolean result = JwtToken.verify(token);

        try {
            DecodedJWT jwt = JwtToken.getJWT(token);

            if(null!=jwt) {
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy‐MM‐dd hh:mm:ss");
                System.out.println("签发时间:" + sdf.format(jwt.getIssuedAt()));
                System.out.println("过期时 间:" + sdf.format(jwt.getExpiresAt()));
                System.out.println("当前时间:" + sdf.format(new Date()));
            }

        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        System.out.println("token is:" + result);

    }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值