实现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<String, Claim> 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<String, Claim> 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<String, Claim> 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,至于在什么位置调用什么的,要考虑自己的业务,不过大多是验证用户,相当于一个令牌

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值