|
1
2
|
package com.huaheng.framework.token;
|
|
3
|
|
|
4
|
import com.huaheng.common.exception.service.ServiceException;
|
|
5
|
import com.huaheng.common.support.Convert;
|
|
6
7
8
9
10
11
|
import com.huaheng.framework.redis.RedisCache;
import com.huaheng.pc.system.user.domain.User;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jws;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
|
|
12
13
|
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
|
|
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
|
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.Calendar;
import java.util.Date;
import java.util.Map;
import java.util.concurrent.TimeUnit;
/**
* token生成与解析
* @author Enzo Cotter
* @date 2020/6/11
*/
@Service
public class TokenService {
@Resource
private RedisCache redisCache;
|
|
33
34
35
|
private static final Logger log = LoggerFactory.getLogger(TokenService.class);
|
|
36
37
38
39
40
41
42
43
44
45
|
/**
* 有效期7天
*/
private static final int EXPIRE_TIME = 7;
/**
* 盐
*/
private static final String signingKey = "secret";
|
|
46
|
|
|
47
48
49
50
51
52
53
|
/**
* 创建token
* @param user 用户
* @return
*/
public String createToken(User user){
Claims claims = Jwts.claims();
|
|
54
|
claims.put("username", user.getLoginName());
|
|
55
56
|
String token = Jwts.builder().setClaims(claims)
.signWith(SignatureAlgorithm.HS512,signingKey).compact();
|
|
57
|
|
|
58
59
60
61
62
63
64
|
if (redisCache.setCacheObject(token, user.toString(), EXPIRE_TIME, TimeUnit.DAYS) == null) {
throw new ServiceException("redis异常");
}
return token;
}
/**
|
|
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
|
* 创建token
* @param user 用户
* @return
*/
public String createTokenForMobile(User user){
//签发时间
Date iatTime = new Date();
//expire time
Calendar nowTime = Calendar.getInstance();
nowTime.add(Calendar.DATE, EXPIRE_TIME);
Date expireTime = nowTime.getTime();
Claims claims = Jwts.claims();
claims.put("user", user);
claims.setIssuedAt(iatTime);
String token = Jwts.builder().setClaims(claims)
.signWith(SignatureAlgorithm.HS512,signingKey).compact();
// if (redisCache.setCacheObject(token, user.toString(), EXPIRE_TIME, TimeUnit.DAYS) == null) {
// throw new ServiceException("redis异常");
// }
return token;
}
/**
|
|
89
90
91
92
93
94
95
|
* 解析token
* @param token
*/
public void parseToken(String token){
Jws<Claims> jws = Jwts.parser().setSigningKey(signingKey).parseClaimsJws(token);
Claims claims = jws.getBody();
Map<String,String> header = jws.getHeader();
|
|
96
97
|
System.out.println("parse" + header);
log.warn("Token:"+ header);
|
|
98
99
|
}
}
|