jwt 认证工具类

1.引入maven

<!-- jwt 身份认证 -->
<dependency>
    <groupId>com.auth0</groupId>
    <artifactId>java-jwt</artifactId>
    <version>3.8.2</version>
</dependency>
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import com.alibaba.druid.util.StringUtils;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @description:token处理类
 * @author: wushuang
 * @date: 2020/12/3
 */
public class JwtUtils {

    protected static Logger logger = LoggerFactory.getLogger(JwtUtils.class);

    /** token秘钥,请勿泄露,请勿随便修改  */
    public static final String SECRET = "MIYAOXX234234";
    /** token 过期时间: 10天 */
    public static final int calendarField = Calendar.DATE;
    public static final int calendarInterval = 10;

    /**
     * @description:生成token
     */
    public static String createToken(String user_id) throws Exception {
        Calendar nowTime = Calendar.getInstance();
        nowTime.add(calendarField, calendarInterval);
        Date expiresDate = nowTime.getTime();
        return createToken(user_id,expiresDate);
    }
    /**
     * @description:生成token
     */
    public static String createToken(String user_id, Date expiresDate) throws Exception {
        Date iatDate = new Date();
        Map<String, Object> map = new HashMap<>();
        map.put("alg", "HS256");
        map.put("typ", "JWT");

        String token = JWT.create().withHeader(map) // header
                .withClaim("iss", "Service") // payload
                .withClaim("aud", "APP").withClaim("user_id",user_id.toString())
                .withIssuedAt(iatDate) // sign time
                .withExpiresAt(expiresDate) // expire time
                .sign(Algorithm.HMAC256(SECRET)); // signature
        return token;
    }
    /**
     * @description:验证
     */
    public static Map<String, Claim> verifyToken(String token) {
        DecodedJWT jwt = null;
        try {
            JWTVerifier verifier = JWT.require(Algorithm.HMAC256(SECRET)).build();
            jwt = verifier.verify(token);
        } catch (Exception e) {
            logger.error(e.getMessage());
            return null;
        }
        return jwt.getClaims();
    }

    /**
     * @description:根据Token获取user_id
     */
    public static String getAppUID(String token) {
        Map<String, Claim> claims = verifyToken(token);
        Claim user_id_claim = claims.get("user_id");
        if (null == user_id_claim || StringUtils.isEmpty(user_id_claim.asString())) {
            logger.error("token 校验失败");  // token 校验失败, 抛出Token验证非法异常
        }
        return user_id_claim.asString();
    }

    public static void main(String[] args) {
        try {
            System.out.println(JwtUtils.createToken("abc"));
            Map<String, Claim> map = JwtUtils.verifyToken("eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJhdWQiOiJBUFAiLCJ1c2VyX2lkIjoiYWJjIiwiaXNzIjoiU2VydmljZSIsImV4cCI6MTYwNzgzOTUwNywiaWF0IjoxNjA2OTc1NTA3fQ.jkqeN-NEgYgpAO9Si7WVGl9hHS-8e_q51KXcx780mg8");
            System.out.println(map);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值