AccountJwtProvider.java
1.9 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
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.account.entity.Account;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.summerframework.web.auth.AbstractJwtProvider;
import java.util.Date;
/**
* JWT认证服务
*/
@Slf4j
@Component
public class AccountJwtProvider extends AbstractJwtProvider {
protected static final String MOBILE = "mobile";
protected static final String AVATAR = "avatar";
/**
* 生成token
*
* @param account user
* @return token
*/
public String generateAccount(Account account) {
try {
return JWT.create()
.withIssuer(jwtProperties.getIssuer())
.withIssuedAt(new Date())
.withExpiresAt(new Date(System.currentTimeMillis() + jwtProperties.getExpiration() * 1000))
.withJWTId(String.valueOf(account.getAccountId()))
.withSubject(account.getAccountName())
.withClaim(MOBILE, account.getMobile())
.sign(algorithm);
} catch (IllegalArgumentException | TokenExpiredException e) {
return null;
}
}
/**
* 解析token
*
* @param token token
* @return User
*/
public Account verifyAccount(String token) {
if (token == null) {
return null;
}
Account account = null;
try {
DecodedJWT jwt = verifier.verify(token);
// 获取用户的权限
String mobile = jwt.getClaim(MOBILE).asString();
account = new Account(Integer.parseInt(jwt.getId()), jwt.getSubject(), mobile);
} catch (Exception e) {
log.error("token解析失败");
}
return account;
}
}