TokenUtils.java 2.59 KB
Newer Older
谢恒's avatar
谢恒 committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74
package com.hs.admin.util;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.hs.admin.base.CodeMessageEnum;
import com.hs.admin.base.HsRuntimeException;
import com.hs.admin.bean.User;

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

/**
 * @author xieheng
 * @desc 使用token验证用户是否登录
 **/
public class TokenUtils {
    //设置过期时间
    private static final long EXPIRE_DATE = 30 * 60 * 100000;
    //token秘钥
    private static final String TOKEN_SECRET = "HSfasfhuaUUHufguGuwu2020BQWE";

    public static String token(String username, String password) {

        String token;
        try {
            //过期时间
            Date date = new Date(System.currentTimeMillis() + EXPIRE_DATE);
            //秘钥及加密算法
            Algorithm algorithm = Algorithm.HMAC256(TOKEN_SECRET);
            //设置头部信息
            Map<String, Object> header = new HashMap<>();
            header.put("typ", "JWT");
            header.put("alg", "HS256");
            //携带username,password信息,生成签名
            token = JWT.create()
                    .withHeader(header)
                    .withClaim("username", username)
                    .withClaim("password", password).withExpiresAt(date)
                    .sign(algorithm);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
        return token;
    }

    public static User verify(String token) {
        /**
         * @desc 验证token,通过返回true
         * @params [token]需要校验的串
         **/
        try {
            Algorithm algorithm = Algorithm.HMAC256(TOKEN_SECRET);
            JWTVerifier verifier = JWT.require(algorithm).build();
            DecodedJWT jwt = verifier.verify(token);
            String username = jwt.getClaim("username").asString();
            String password = jwt.getClaim("password").asString();
            return new User(username, password);
        } catch (Exception e) {
            throw new HsRuntimeException(CodeMessageEnum.REQUEST_ERROR.getCode(),"token错误");
        }
    }

    public static void main(String[] args) {
        String username = "zhangsan";
        String password = "123";
        String token = token(username, password);
        User user = verify("eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJwYXNzd29yZCI6IjEyMyIsImV4cCI6MTYyMDY0MTEzNywidXNlcm5hbWUiOiJ6aGFuZ3NhbiJ9.TIFCrGeFCzFiviwUUIS29hklA3fZDXTwb8EZwwb8JiQ1");
        System.out.println(token);
    }
}