文章目录
前言
提示:这里可以添加本文要记录的大概内容:
一、jwt做登录鉴权
1.1 写出jwt 生成token 的工具类
1.1.1 编写获取token工具类方法(getToken() )
思路:
一、首先考虑要接收的参数。要知道用户的ID或者用户名、角色等。因此这里把这三个属性封装到一个AuthInfo对象中。还要传入过期时间 和加密字符串信息。
@Data
public class AuthInfo {
private Long UserId;
private String userName;
private String roles;
}
public static String getToken(AuthInfo authInfo, Date expireDate, String secret){
return "";
}
二、 进入方法时,首先判断参数是否为空,这里我们可以使用谷歌的包:com.google.common.base.Preconditions;里面有对应的API可以非常方便的做验证。
代码:
//做验证
Preconditions.checkArgument(authInfo != null,"加密内容不能为null");
Preconditions.checkArgument(expireDate != null,"过期时间异常");
Preconditions.checkArgument(secret != null,"加密密码不能为null");
三、使用JWT的Api调用方法,将Header和签名等参数赋值。
Map<String, Object> map = new HashMap<>();
// 固定格式
map.put("alg", "HS256");
map.put("typ", "JWT");
String token = null;//签名
try {
token = JWT.create()
.withHeader(map)//头
// 参数
.withClaim(USER_ID,authInfo.getUserId())
.withClaim(USER_NAME,authInfo.getUserName())
.withClaim(USER_ROLES,authInfo.getRoles())
.withIssuedAt(new Date())//签名时间
.withExpiresAt(expireDate)//过期时间
.sign(Algorithm.HMAC256(secret));
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (JWTCreationException e) {
e.printStackTrace();
}
四、返回token 字符串,下面是完整代码:
package com.tzw.gene.utils;
import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTCreationException;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.auth0.jwt.interfaces.JWTVerifier;
import com.google.common.base.Preconditions;
import com.tzw.gene.auth.AuthInfo;
import java.util.Date;
import java.util.HashMap