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
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.stereotype.Service;

import javax.crypto.spec.SecretKeySpec;
import java.security.Key;
import java.util.Base64;
import java.util.UUID;

/**
* Create by liping on 2018/9/25
*/
@Service
public class JWTService {
private static final String encodekeys = "liping";

private static SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS512;
private static Key key;

// @Value("${com.idoipo.jwt.encodedKey}")
// private String encodedKey;

/**
* 初始化操作 @PostConstruct初始化完成后执行
*/
// @PostConstruct
// public void init() {
// signatureAlgorithm = SignatureAlgorithm.HS512;
// key = deserializeKey(encodedKey);
// }

/**
* 生成加密解密key
* @return
*/
public static Key deserializeKey() {
byte[] decodedKey = Base64.getDecoder().decode(encodekeys);

Key key = new SecretKeySpec(decodedKey, JWTService.signatureAlgorithm.getJcaName());
return key;
}

/**
* 创建token 参数应该为自定义模型去传,用来设置token所携带字段
* @return
*/
public static String createToken(){
key = deserializeKey();
String token = Jwts.builder()
.setSubject(UUID.randomUUID().toString())
.claim("userName", "liping")
.setIssuer("lp")
.setAudience("xixi")
.signWith(signatureAlgorithm, key).compact();
return token;
}

public static String parseToken(String token){
key = deserializeKey();
Claims claims = Jwts.parser().setSigningKey(key).parseClaimsJws(token).getBody();
return claims.get("userName").toString();
}

public static void main(String[] args) {
String token = JWTService.createToken();
System.out.println(token);
String userName = JWTService.parseToken(token);
System.out.println(userName);
}



}