提交 58eb89b2 编写于 作者: 别团等shy哥发育's avatar 别团等shy哥发育

添加JWT工具类

上级 bd01a9e0
...@@ -10,6 +10,12 @@ ...@@ -10,6 +10,12 @@
<modelVersion>4.0.0</modelVersion> <modelVersion>4.0.0</modelVersion>
<artifactId>common-util</artifactId> <artifactId>common-util</artifactId>
<dependencies>
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt</artifactId>
</dependency>
</dependencies>
</project> </project>
\ No newline at end of file
package com.atguigu.yygu.common.helper;
import io.jsonwebtoken.*;
import org.springframework.util.StringUtils;
import java.util.Date;
/**
* JWT工具类
*/
public class JwtHelper {
//过期时间
private static long tokenExpiration = 24*60*60*1000;
//token签名密钥
private static String tokenSignKey = "123456";
//根据参数生成token
public static String createToken(Long userId, String userName) {
String token = Jwts.builder()
.setSubject("YYGH-USER")
//设置过期时间 30分钟
.setExpiration(new Date(System.currentTimeMillis() + tokenExpiration))
//设置主题信息 用户id和用户名称
.claim("userId", userId)
.claim("userName", userName)
//签名哈希
.signWith(SignatureAlgorithm.HS512, tokenSignKey)
.compressWith(CompressionCodecs.GZIP)
.compact();
return token;
}
//根据token字符串得到用户id
public static Long getUserId(String token) {
if(StringUtils.isEmpty(token)) return null;
Jws<Claims> claimsJws = Jwts.parser().setSigningKey(tokenSignKey).parseClaimsJws(token);
Claims claims = claimsJws.getBody();
Integer userId = (Integer)claims.get("userId");
return userId.longValue();
}
//根据token字符串得到用户名称
public static String getUserName(String token) {
if(StringUtils.isEmpty(token)) return "";
Jws<Claims> claimsJws
= Jwts.parser().setSigningKey(tokenSignKey).parseClaimsJws(token);
Claims claims = claimsJws.getBody();
return (String)claims.get("userName");
}
public static void main(String[] args) {
String token = JwtHelper.createToken(1L, "lucy");
System.out.println(token);
System.out.println(JwtHelper.getUserId(token));
System.out.println(JwtHelper.getUserName(token));
}
}
...@@ -20,7 +20,7 @@ public enum ResultCodeEnum { ...@@ -20,7 +20,7 @@ public enum ResultCodeEnum {
CODE_ERROR(210, "验证码错误"), CODE_ERROR(210, "验证码错误"),
// LOGIN_MOBLE_ERROR(211, "账号不正确"), // LOGIN_MOBLE_ERROR(211, "账号不正确"),
LOGIN_DISABLED_ERROR(212, "用户已被禁用"), LOGIN_DISABLED_ERROR(212, "用户已被禁用"),
REGISTER_MOBLE_ERROR(213, "手机号已被使用"), REGISTER_MOBLE_ERROR(213, "手机号已被使用"),
LOGIN_AURH(214, "需要登录"), LOGIN_AURH(214, "需要登录"),
LOGIN_ACL(215, "没有权限"), LOGIN_ACL(215, "没有权限"),
......
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册