有的时候我们需要传给后端一个值,只能通过前端的 token获取这个值,然后传给后端
后端生成Token 的方法
private String jwtToken(String userId, String username, String role) {
return JWT.create()
.withClaim("userId", userId)
.withClaim("username", username)
.withClaim("role", role)
.withClaim("expireAt", expireTime())
.sign(Algorithm.HMAC256(jwtSecret));
}
登录成功之后,我们想在前端获取 token 中的值,如:userId,role等,需要解析该token。
请求解析token的URL:
this.axios.get('/login-user-info')
.then(res => {
if (res.data) {
// 解析成功
// 获取从token中解析到的值
this.userInfo.jwtToken = res.data.jwtToken;
this.userInfo.userId = res.data.userId;
this.userInfo.username = res.data.username;
this.userInfo.role = res.data.role;
//将变量 licence,token,username 添加到缓存中
localStorage.setItem("locate.licence", res.data["licence"]);
localStorage.setItem("locate.token", res.data["token"]);
localStorage.setItem("locate.username", this.userInfo.username);
}
})
后端解析Token 的接口代码
@ApiOperation("当前登录用户信息")
@GetMapping("/login-user-info")
public ReturnMsg loginUserInfo(HttpServletRequest request) {
String token = request.getHeader(jwtHeader);
if (Strings.isNullOrEmpty(token)) {
return ReturnMsg.defaultSuccessResult();
}
JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(jwtSecret)).build();
try {
DecodedJWT verify = jwtVerifier.verify(token);
String username = verify.getClaim("username").asString();
String role = verify.getClaim("role").asString();
Long expireAt = verify.getClaim("expireAt").asLong();
//token参数不对
if (!Strings.isNullOrEmpty(username)
&& !Strings.isNullOrEmpty(role) && expireAt != null
&& expireAt > System.currentTimeMillis()) {
Optional<BuildingManagerBO> bm = buildingManagerService.findByUsername(username);
LoginUserInfoVO loginUserInfoVO = bm.map(bo -> new LoginUserInfoVO(token, role, bo.getUserId(), bo.getUsername(), bo.getLicence(),
bo.getBuildCount())).orElse(null);
return ReturnMsg.wrapSuccessfulResult(loginUserInfoVO);
}
} catch (JWTVerificationException ignore) {
//验证失败
}
return ReturnMsg.defaultSuccessResult();
}