JWT

package com.box.common.core.utils;

/**
* 文件描述
*
* @author yuan.dingwang
* @date 2020年11月26日 17:13
*/

public class JWTToken {

private String access_token;
private String token_type;
private Long expires_in;

private Object date;

public String getAccess_token() {
return access_token;
}

public void setAccess_token(String access_token) {
this.access_token = access_token;
}

public String getToken_type() {
return token_type;
}

public void setToken_type(String token_type) {
this.token_type = token_type;
}

public Long getExpires_in() {
return expires_in;
}

public void setExpires_in(Long expires_in) {
this.expires_in = expires_in;
}

public Object getDate() {
return date;
}

public void setDate(Object date) {
this.date = date;
}
}

JWTToken token = JwtUtils.creatToke(user.getId(), body, newRoles, platform);
StringBuffer key = new StringBuffer(CacheKeyConstant.CECHE_MANAGE_USER_TOKEN).append(platform).append(":").append(user.getId());
redisService.set(key.toString(), token.getAccess_token(), token.getExpires_in() / 1000L);



package com.box.common.core.utils;

import com.alibaba.fastjson.JSONObject;
import com.box.common.core.enums.ErrorCodeEnum;
import com.box.common.core.enums.PlatformEnum;
import com.box.common.core.exception.AuthException;
import com.box.common.core.login.AppLoginInfo;
import com.box.common.core.login.BaseLoginInfo;
import com.box.common.core.login.ManageLoginInfo;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.apache.tomcat.util.codec.binary.Base64;

import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.util.Date;

/**
* jwt
*
* @author yuan.dingwang
* @date 2020年11月26日 16:59
*/

public class JwtUtils {

private static final String JWT_KEY = "box_mall_toke_";
/*
private static final int EXPIRE = 7;

private static final String SECRET = "OpenAPI#LingZeTechCo.,Ltd.@2020";

private static final String ISSUER = "LingZe Tech Co.,Ltd.";

private static final Algorithm ALGORITHM = Algorithm.HMAC256(SECRET);

private static Date getExpiresAt(int days) {
Instant instant = new Date().toInstant();
ZoneId zone = ZoneId.systemDefault();
LocalDateTime date = LocalDateTime.ofInstant(instant, zone).plusDays(days);
return Date.from(date.atZone(zone).toInstant());
}
*/

/**
* 生成JWT
*
* @param body
* @param role
* @return
*/
public static JWTToken creatToke(String uid, BaseLoginInfo body, String role, Integer platform) {
Long expires_in = 1000 * 60 * 60 * 24L; //一天
long time = System.currentTimeMillis();
time = time + expires_in;
return saveToken(uid, JSONObject.toJSONString(body), role, time, platform);
}

/**
* 生成JWT
*
* @param body
* @param role
* @return
*/
public static JWTToken creatBoxAppToke(String uid, AppLoginInfo body) {
Long expires_in = 1000 * 60 * 60 * 24L; //一天
long time = System.currentTimeMillis();
time = time + expires_in;
return saveToken(uid, JSONObject.toJSONString(body), "CUSER", time,PlatformEnum.BOX_C_APP.getCode());
}

private static JWTToken saveToken(String uid, String body, String role, long time, Integer platform) {
JwtBuilder builder = Jwts.builder()
.setId(uid) //设置唯一ID
.setSubject(body) //设置内容,这里用JSON包含帐号信息
.setIssuedAt(new Date()) //签发时间
//.setExpiration(getExpiresAt(EXPIRE)) //过期时间
.setExpiration(new Date(time))
.claim("roles", role) //设置角色
.signWith(SignatureAlgorithm.HS256, generalKey(platform)) //设置签名 使用HS256算法,并设置密钥
;
String code = builder.compact();
JWTToken token = new JWTToken();
token.setAccess_token(code);
token.setExpires_in(time);
token.setToken_type("JWT");
return token;
}

/**
* 解析JWT
*
* @param jwt
* @return
*/
public static Claims parseJWT(String jwt, Integer platform) {
Claims body = Jwts.parser().setSigningKey(generalKey(platform)).parseClaimsJws(jwt).getBody();
return body;
}

/**
* 刷新JWT
*
* @param jwt
* @return
*/
public static JWTToken refreshJWT(String jwt, Integer platform) {
Claims claims = parseJWT(jwt, platform);
BaseLoginInfo body = null;
if (platform.intValue() == PlatformEnum.BOX_C_APP.getCode()) {
body = (AppLoginInfo) JSONObject.parse(claims.getSubject());
} else {
body = (ManageLoginInfo) JSONObject.parse(claims.getSubject());
}
String role = claims.get("roles").toString();
return creatToke(claims.getId(), body, role, platform);
}

/**
* 设置过期
*
* @param jwt
* @return
*/
public static JWTToken expireJWT(String jwt, Integer platform) {
Claims claims = parseJWT(jwt, platform);
String body = claims.getSubject();
String role = claims.get("roles").toString();
return saveToken(claims.getId(), body, role, SystemClockUtils.millisClock().now(), platform);
}

/**
* 获取JWT信息
*
* @param jwt
* @return
*/
public static Claims infoJWT(String jwt, Integer platform) {
try {
Claims claims = parseJWT(jwt, platform);
return claims;
} catch (Exception e) {
throw new AuthException(ErrorCodeEnum.HEAD_GET_USER_NULL);
}

}


/**
* 验证JWT
*
* @param jwt
* @return
*/
public static boolean checkJWT(String jwt, Integer platform) {
try {
Claims body = Jwts.parser().setSigningKey(generalKey(platform)).parseClaimsJws(jwt).getBody();
if (body != null) {
return true;
}
} catch (Exception e) {
return false;
}
return false;
}

/**
* 生成加密后的秘钥 secretKey
*
* @return
*/
public static SecretKey generalKey(Integer platform) {
StringBuffer key = new StringBuffer(JWT_KEY).append(platform);
byte[] encodedKey = Base64.encodeBase64(key.toString().getBytes());
return new SecretKeySpec(encodedKey, 0, encodedKey.length, "AES");
}
}


/**
* 验证token是否有效
*
* @param token
* @return
*/
public boolean checkToken(String token, Integer platform) {
//验证token是否有效
if (StringUtils.isBlank(token)) {
return true;
}
//验证token是否有效
if (!JwtUtils.checkJWT(token, platform)) {
return true;
}
//验证用户是否过期
Claims claims = JwtUtils.infoJWT(token, platform);
if (StringUtils.isNull(claims) || StringUtils.isNull(claims.getId())
|| StringUtils.isNull(claims.get("roles"))) {
return true;
}
return false;
}
小蚊子大人
原文地址:https://www.cnblogs.com/ywsheng/p/14975926.html