Java JWT Token令牌认证

在pom.xml中加入依赖

<dependency>
   <groupId>com.auth0</groupId>
   <artifactId>java-jwt</artifactId>
   <version>3.8.2</version>
</dependency>

import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.exceptions.InvalidClaimException;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;
import java.io.UnsupportedEncodingException;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @Description 令牌处理器
 * @Author WangKun
 * @Date 2021/6/24 16:09
 * @Version
 */
public class TokenUtil {
    /**
     * token加解密秘钥
     **/
    private static final String SECRET_KEY = "WK_0612";

    /**
     * @Description 生成令牌
      * @param userName
     * @param password
     * @param userId
     * @Throws
     * @Return java.lang.String
     * @Date 2021-07-09 16:19:59
     * @Author WangKun
     **/
    public static String createToken(String userName, String password ,String userId) throws UnsupportedEncodingException {
        Calendar calendar1 = Calendar.getInstance();
        Calendar calendar2 = Calendar.getInstance();
        //生效时间
        calendar2.add(Calendar.SECOND, 0);
        Date effectTime = calendar2.getTime();
        //过期时间60min后
        calendar1.add(Calendar.MINUTE, 60);
        Date maturityTime = calendar1.getTime();
        Map<String, Object> header = new HashMap<>(2);
        header.put("alg", "HS256");
        header.put("typ", "JWT");
        return JWT.create()
                .withHeader(header)
                .withClaim("password", password)
                .withClaim("userName", userName)
                .withClaim("userId", userId)
                .withIssuedAt(new Date())
                .withExpiresAt(maturityTime)
                .withNotBefore(effectTime)
                .withJWTId(userId)
                .sign(Algorithm.HMAC256(SECRET_KEY));
    }

    /**
     * @Description 解析验证令牌
      * @param token
     * @Throws
     * @Return java.util.Map<java.lang.String,com.auth0.jwt.interfaces.Claim>
     * @Date 2021-07-09 16:20:17
     * @Author WangKun
     **/
    public static Map<String, Claim> verifyToken(String token) throws UnsupportedEncodingException {
        //秘钥解密
        JWTVerifier verifier = JWT.require(Algorithm.HMAC256(SECRET_KEY)).build();
        DecodedJWT jwt = null;
        try {
            jwt = verifier.verify(token);
        } catch (JWTVerificationException e) {
            e.printStackTrace();
            if (e.getMessage().startsWith("The Token can't be used before")) {
                throw new InvalidClaimException("登录凭证未生效");
            }
            if (e.getMessage().startsWith("The Token has expired on")) {
                throw new InvalidClaimException("登录凭证已过期,请重新登录");
            }
        }
        if (jwt != null) {
            return jwt.getClaims();
        }
        return null;
    }


}
使用:

String token = TokenUtil.createToken(userName,password ,userId);

解析:
Map<String, Claim> claimMap = TokenUtil.verifyToken(token);
String userName = claimMap.get("userName").asString();
String password = claimMap.get("password").asString();
String userId = claimMap.get("userId").asString()

异常信息捕捉
try {
     Map<String, Claim> claimMap = TokenUtil.verifyToken(token);
     // 业务处理(token正常情况下处理)
 } catch (Exception e) {
   // token不正常情况下处理,返回异常信息
   JSONObject objet = new JSONObject();
   objet.put("status", false);
   objet.put("msg", e.getMessage());
   Writer out = resp.getWriter();
   out.write(objet.toString());
 }

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值