guyue
5 天以前 e285517df2a3cb206282a41f958c80044422a552
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
package com.linghu.utils;
 
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
 
import com.linghu.model.entity.User;
 
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.MalformedJwtException;
import io.jsonwebtoken.SignatureAlgorithm;
import io.jsonwebtoken.UnsupportedJwtException;
import io.jsonwebtoken.security.Keys;
import io.jsonwebtoken.security.SignatureException;
 
import javax.crypto.SecretKey;
import java.util.Date;
import java.util.Map;
 
@Component
public class JwtUtils {
    @Value("${jwt.secret}")
    private final String secret;
 
    @Value("${jwt.expiration}")
    private final Long expiration;
 
    // 生成安全的密钥
    private SecretKey getSigningKey() {
        return Keys.hmacShaKeyFor(secret.getBytes());
    }
 
    // 通过构造函数注入配置值
    public JwtUtils(
            @Value("${jwt.secret}") String secret,
            @Value("${jwt.expiration}") long expiration) {
 
        this.secret = secret;
        this.expiration = expiration;
    }
 
    public String generateToken(User user) {
        SecretKey key = Keys.hmacShaKeyFor(secret.getBytes());
 
        return Jwts.builder()
                .setSubject(user.getUser_name())
                .claim("email", user.getUser_email())
                .setIssuedAt(new Date())
                .setExpiration(new Date(System.currentTimeMillis() + expiration * 1000))
                .signWith(key, SignatureAlgorithm.HS256)
                .compact();
    }
 
    public User parseToken(String token)
            throws ExpiredJwtException, UnsupportedJwtException,
            MalformedJwtException, SignatureException, IllegalArgumentException {
 
        Claims claims = Jwts.parser()
                .setSigningKey(getSigningKey())
                .build()
                .parseClaimsJws(token)
                .getBody();
 
        // 创建User对象并填充数据
        User user = new User();
        user.setUser_name(claims.getSubject()); // 主题是用户名
        user.setUser_email(claims.get("email", String.class));
 
        // 添加角色信息(如果存在)
        // if (claims.containsKey("roles")) {
        // user.setRoles(claims.get("roles", String.class));
        // }
 
        return user;
    }
 
    public boolean validateToken(String token) {
        try {
            parseToken(token);
            return true;
        } catch (Exception e) {
            return false;
        }
    }
}