JwtProvider.java
2.93 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
package com.glsx.usedcar.web;
import com.auth0.jwt.JWT;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.glsx.usedcar.module.security.entity.User;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.stereotype.Component;
import org.summerframework.storage.domain.FileInfo;
import org.summerframework.web.auth.AbstractJwtProvider;
import java.util.Date;
import java.util.HashSet;
import java.util.Set;
/**
* JWT认证服务
*/
@Slf4j
@Component
public class JwtProvider extends AbstractJwtProvider {
protected static final String REAL_NAME = "realName";
protected static final String AVATAR = "avatar";
/**
* 生成token
*
* @param user user
* @return token
*/
public String generateUser(User user) {
String[] roleCodes = user.getAuthorities().stream().map(GrantedAuthority::getAuthority).toArray(String[]::new);
try {
return JWT.create()
.withIssuer(jwtProperties.getIssuer())
.withIssuedAt(new Date())
.withExpiresAt(new Date(System.currentTimeMillis() + jwtProperties.getExpiration() * 1000))
.withJWTId(String.valueOf(user.getUserId()))
.withSubject(user.getUsername())
.withClaim(CLAIM_PASSWORD, user.getPassword())
.withArrayClaim(CLAIM_AUTHORITIES, roleCodes)
.withClaim(REAL_NAME, user.getRealName())
.sign(algorithm);
} catch (IllegalArgumentException | TokenExpiredException e) {
return null;
}
}
/**
* 解析token
*
* @param token token
* @return User
*/
public User verifyUser(String token) {
if (token == null) {
return null;
}
try {
DecodedJWT jwt = verifier.verify(token);
// 获取用户的权限
String[] roles = jwt.getClaim(CLAIM_AUTHORITIES).asArray(String.class);
String password = jwt.getClaim(CLAIM_PASSWORD).asString();
String realName = jwt.getClaim(REAL_NAME).asString();
String avatar = jwt.getClaim(AVATAR).asString();
Set<GrantedAuthority> grantedAuthorities = new HashSet<>();
for (String securityRole : roles) {
grantedAuthorities.add(new SimpleGrantedAuthority(securityRole));
}
User user = new User(Integer.parseInt(jwt.getId()), jwt.getSubject(), grantedAuthorities);
user.setRealName(realName);
FileInfo empty = FileInfo.empty();
empty.setFilePath(avatar);
// user.setAvatar(empty);
user.setPassword(password);
return user;
} catch (Exception e) {
return null;
}
}
}