实现token

每天一篇之token实现

现在web开发基本上都会涉及到token,至于为什么要用这些就不再解释,,就默默发一个token的util,下面是代码

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTCreationException;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;
import org.springframework.util.StringUtils;

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


/**
 * @author w
 * @Date 2018/7/18 12:57
 */

public class TokenProvider {


    private static String secretKey = "g1UkiJ97M1Xx53fk1udTN7bBYoYAbrUqcUf1jIjaNwAw5JP01x"; //签名密钥


    /**
     * @param tokenInfo token需要携带的信息  比如用户id之类的
     * @param expireTime  过期时间 这个很重要
     * @return
     * @throws JWTCreationException
     * @description 根据认证信息生成新token
     */
    static public String createToken(String tokenInfo, Long expireTime) throws JWTCreationException {
        Algorithm algorithm = Algorithm.HMAC256(secretKey);
        if (expireTime != null){
            expireTime+=expireTime*60*1000;
        }
        JWTCreator.Builder builder = JWT.create().withClaim("info", tokenInfo);
        return builder.withIssuer("auth0")
                .withExpiresAt(new Date(new Date().getTime() + expireTime))
                .sign(algorithm);
    }

    /**
     * @param token
     * @return
     * @description 获取token里面的数据, 过期抛出异常
     */
    static public String getTokenInfo(String token) throws JWTVerificationException {
        if (StringUtils.isEmpty(token)) throw new JWTVerificationException("token require is not null");
        Algorithm algorithm = Algorithm.HMAC256(secretKey);
        JWTVerifier verifier = JWT.require(algorithm)
                .withIssuer("auth0")
                .build();
        DecodedJWT jwt = verifier.verify(token);
        Map result = new HashMap();
        for (Map.Entry entry : jwt.getClaims().entrySet()) {
            result.put(entry.getKey(), entry.getValue().asString());
        }
        return String.valueOf(result.get("info"));
    }


    /**
     * @param token
     * @return
     * @throws JWTDecodeException
     * @description 不管该token是否过期都获取token里面的数据
     */
    static private Map getClaimsIgnoreExpire(String token) throws JWTVerificationException {
        if (token == null) throw new JWTDecodeException("token require is not null");
        DecodedJWT jwt = JWT.decode(token);
        return jwt.getClaims();
    }

    /**
     * @param token
     * @return
     * @throws JWTDecodeException
     * @description 获取载荷数据里的exp字段
     */
    static Long getExp(String token) throws JWTVerificationException {
        if (token == null) throw new JWTDecodeException("Token require is not null");
        Map claim = getClaimsIgnoreExpire(token);
        if (claim.get("exp") == null) throw new JWTDecodeException("The token have no exp field");
        return claim.get("exp").asLong();
    }


    /**
     * @param token
     * @return
     * @throws JWTDecodeException
     * @description 通过exp字段判断token是否过期
     */
    public static boolean isExpire(String token) throws JWTVerificationException {
        Long exp = getExp(token);
        return (new Date().getTime() / 1000) - exp.longValue() > 0 ? true : false;
    }
}

这就是util,至于在什么位置调用什么的,要考虑自己的业务,不过大多是验证用户,相当于一个令牌

你可能感兴趣的:(实现token)