当前位置: 代码迷 >> 综合 >> JWT生成token和验证的简单实现
  详细解决方案

JWT生成token和验证的简单实现

热度:94   发布时间:2023-10-21 14:59:55.0

给客户提供数据接口时,要求使用jwt生成token实现token认证

首先引入依赖:

<!-- JWT -->
<dependency><groupId>com.auth0</groupId><artifactId>java-jwt</artifactId><version>3.7.0</version>
</dependency>

 

工具类:

package com.app.utils;import java.util.Date;
import java.util.HashMap;
import java.util.Map;import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.auth0.jwt.interfaces.DecodedJWT;/*** @title jwt Token工具类* @author zch* @discribtion* @Date 2020年1月7日 下午4:12:46* @vision 	V1.0*/
public class JWTUtil
{// 有效时长毫秒数private static final long EXPIRE_TIME = 30 * 60 * 1000;// token 密钥private static final String TOKEN_SECRET = "testsecret";/*** @title 生成token* @discribtion* @author zch* @Date 2020年1月7日 下午4:10:32* @vision V1.0*/public static String generateToken(String userId){try{Date date = new Date(System.currentTimeMillis() + EXPIRE_TIME);Algorithm algorithm = Algorithm.HMAC256(TOKEN_SECRET);// 设置头部信息Map<String, Object> header = new HashMap<String, Object>();header.put("typ", "JWT");header.put("alg", "HS256");String token = JWT.create().withHeader(header) // header.withClaim("userId", userId).withExpiresAt(date) // 过期时间.sign(algorithm); // 签名return token;}catch (IllegalArgumentException e){e.printStackTrace();return null;}}/*** @title 校验token* @discribtion* @author zch* @Date 2020年1月7日 下午4:10:51* @return 0 校验通过, 1 token已过期, 2 校验不通过* @vision V1.0*/public static int verify(String token){int flag;try{Algorithm algorithm = Algorithm.HMAC256(TOKEN_SECRET);JWT.require(algorithm).build().verify(token);flag = 0;// 校验通过}catch (TokenExpiredException e){e.printStackTrace();flag = 1;// token过期}catch (JWTVerificationException e){e.printStackTrace();flag = 2;// 校验失败}return flag;}/*** @title 获取token中的用户id* @discribtion* @author zch* @Date 2020年1月7日 下午4:11:52* @vision V1.0*/public static String getUserId(String token){DecodedJWT jwt = JWT.decode(token);return jwt.getClaim("userId").asString();}
}

 

在拦截器中进行验证

戳这里看

 

又要求每次获取新token后使旧token失效

emmm,JWT操作token没有使其立即失效的方法

利用数据库,保存用户的token信息,生成新的则替换旧的,在拦截器中增加一次校验

 

 

 

  相关解决方案