0.9.1
public class JwtUtils {
private static String signKey = "abcdefghijklmnopqrstuvwxyzqwertyuiopasdfghjklzxcvbnm";
private static Long expire = 43200000L;
/**
* 生成JWT令牌
* @param claims JWT第二部分负载 payload 中存储的内容
* @return
*/
public static String generateJwt(Map<String, Object> claims){
String jwt = Jwts.builder()
.addClaims(claims)
.signWith(SignatureAlgorithm.HS256, signKey)
.setExpiration(new Date(System.currentTimeMillis() + expire))
.compact();
return jwt;
}
/**
* 解析JWT令牌
* @param jwt JWT令牌
* @return JWT第二部分负载 payload 中存储的内容
*/
public static Claims parseJWT(String jwt){
Claims claims = Jwts.parser()
.setSigningKey(signKey)
.parseClaimsJws(jwt)
.getBody();
return claims;
}
}
0.12.3
@Component
@ConfigurationProperties(prefix = "sky.jwt")
@Data
public class JwtProperties {
/**
* 管理端员工生成jwt令牌相关配置
*/
private String adminSecretKey;
public SecretKey getAdminSecretKey() {
return Keys.hmacShaKeyFor(Decoders.BASE64.decode(adminSecretKey));
}
private long adminTtl;
private String adminTokenName;
/**
* 用户端微信用户生成jwt令牌相关配置
*/
private String userSecretKey;
public SecretKey getUserSecretKey() {
return Keys.hmacShaKeyFor(Decoders.BASE64.decode(userSecretKey));
}
private long userTtl;
private String userTokenName;
}
public class JwtUtils {
/**
* 生成token令牌(jwt)
* 使用Hs256算法
* @param claims 设置的信息
* @return
*/
public static String createToken(SecretKey secretKey, long ttlMillis,Map<String, Object> claims){
String token = Jwts.builder()
//设置签名使用的签名算法和签名使用的秘钥
.signWith(secretKey, Jwts.SIG.HS256)
.expiration(new Date(System.currentTimeMillis()+ttlMillis)) //设置token有效时长
.claims(claims) //设置自定义负载信息
.compact(); //设置过期时间
return token;
}
/**
* 先解析jwt
* 再从Token中获取负载中的Claims:getPayload();
* @param token token
* @return 负载
*/
public static Claims getPayload(SecretKey secretKey,String token)
{
return Jwts.parser()
.verifyWith(secretKey)
.build()
.parseSignedClaims(token)
.getPayload();
}
}
使用
public Result login(@RequestBody Emp emp){
log.info("员工登录:{}",emp);
Emp e= empService.login(emp);
Map<String,Object>map = new HashMap<>();
map.put("empId",employee.getId());
String token = JwtUtil.createToken(
jwtProperties.getAdminSecretKey(),
jwtProperties.getAdminTtl(),
map);
EmployeeLoginVO employeeLoginVO = EmployeeLoginVO.builder()
.id(employee.getId())
.userName(employee.getUsername())
.name(employee.getName())
.token(token)
.build();
return Result.success(employeeLoginVO);
}