2021与蓝度共同重构项目,服务端
chenjiantian
2021-11-24 6bdb5dda11b8723ddc20a37b9cbcc1e1fdace13a
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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
package com.sandu.common.security.jwt;
 
import com.sandu.common.security.config.SecurityProperties;
import io.jsonwebtoken.*;
import io.jsonwebtoken.io.Decoders;
import io.jsonwebtoken.security.Keys;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.stereotype.Component;
 
import javax.servlet.http.HttpServletRequest;
import java.security.Key;
import java.util.Arrays;
import java.util.Collection;
import java.util.Date;
import java.util.stream.Collectors;
 
/**
 * @author chenjiantian
 * @date 2021/4/23 16:43
 */
@Slf4j
@Component
public class JwtTokenProvider implements InitializingBean {
 
    private static final String AUTHORITIES_KEY = "auth";
    private static final String CREDENTIALS_KEY = "cred";
    private final SecurityProperties properties;
    private Key key;
 
    public JwtTokenProvider(SecurityProperties properties) {
        this.properties = properties;
    }
 
    @Override
    public void afterPropertiesSet() throws Exception {
        byte[] keyBytes = Decoders.BASE64.decode(properties.getBase64Secret());
        this.key = Keys.hmacShaKeyFor(keyBytes);
    }
 
    /**
     * 根据认证信息生成一个token
     */
    public String createToken(Authentication authentication) {
 
        String authorities = authentication.getAuthorities().stream()
                .map(GrantedAuthority::getAuthority)
                .collect(Collectors.joining(","));
 
        long now = (new Date()).getTime();
        Date expiration = new Date(now + properties.getTokenValidityInSeconds());
 
        return Jwts.builder()
                .setSubject(authentication.getName())
                .claim(AUTHORITIES_KEY, authorities)
                .claim(CREDENTIALS_KEY, authentication.getCredentials())
                .setExpiration(expiration)
                .signWith(key, SignatureAlgorithm.HS512)
                .compact();
    }
 
 
 
    /**
     * 根据token获取认证信息
     */
    public Authentication getAuthentication(String token) {
        Claims claims = Jwts.parserBuilder()
                .setSigningKey(key)
                .build()
                .parseClaimsJws(token)
                .getBody();
 
        Collection<? extends GrantedAuthority> authorities =
                Arrays.stream(claims.get(AUTHORITIES_KEY).toString().split(","))
                        .map(SimpleGrantedAuthority::new)
                        .collect(Collectors.toList());
 
        User principal = new User(claims.getSubject(), "", authorities);
 
        return new UsernamePasswordAuthenticationToken(principal, claims.get(CREDENTIALS_KEY), authorities);
    }
 
    /**
     * 验证token有效性
     */
    public boolean validateToken(String authToken) {
        try {
            Jwts.parserBuilder().setSigningKey(key).build().parseClaimsJws(authToken);
            return true;
        } catch (io.jsonwebtoken.security.SecurityException | MalformedJwtException e) {
            log.info("Invalid JWT signature.");
            e.printStackTrace();
        } catch (ExpiredJwtException e) {
            log.info("Expired JWT token.");
            e.printStackTrace();
        } catch (UnsupportedJwtException e) {
            log.info("Unsupported JWT token.");
            e.printStackTrace();
        } catch (IllegalArgumentException e) {
            log.info("JWT token compact of handler are invalid.");
            e.printStackTrace();
        }
        return false;
    }
 
    /**
     * 获取请求头的token
     */
    public String getToken(HttpServletRequest request) {
        final String requestHeader = request.getHeader(properties.getHeader());
        if (requestHeader != null && requestHeader.startsWith(properties.getTokenStartWith())) {
            return requestHeader.substring(properties.getTokenStartWith().length());
        }
        return null;
    }
 
    public Throwable getException(String authToken) {
        try {
            Jwts.parserBuilder().setSigningKey(key).build().parseClaimsJws(authToken);
            return null;
        } catch (Exception e) {
            return e;
        }
    }
 
    /**
     * 获取Claims 不论是不是jwt过期
     * @param token
     * @return
     */
    public Claims getClaimsForce(String token) {
        try {
            Claims claims = Jwts.parserBuilder()
                    .setSigningKey(key)
                    .build()
                    .parseClaimsJws(token)
                    .getBody();
            return claims;
        } catch (io.jsonwebtoken.security.SecurityException | MalformedJwtException e) {
            log.info("Invalid JWT signature.");
        } catch (ExpiredJwtException e) {
            log.info("Expired JWT token.");
            return e.getClaims();
        } catch (UnsupportedJwtException e) {
            log.info("Unsupported JWT token.");
        } catch (IllegalArgumentException e) {
            log.info("JWT token compact of handler are invalid.");
        }
 
        return null;
    }
 
    /**
     * 获取subject 不论是不是jwt过期
     * @param token
     * @return
     */
    public String getSubjectForce(String token) {
        Claims claimsForce = getClaimsForce(token);
        if(claimsForce != null){
            return claimsForce.getSubject();
        }
        return null;
    }
 
    /**
     * 刷新token 把过期的token 刷新
     * @param oldToken
     * @return
     */
    public String refreshToken(String oldToken) {
 
        Claims claimsForce = getClaimsForce(oldToken);
        if(claimsForce == null){
            return null;
        }
 
        Collection<? extends GrantedAuthority> authorities =
                Arrays.stream(claimsForce.get(AUTHORITIES_KEY).toString().split(","))
                        .map(SimpleGrantedAuthority::new)
                        .collect(Collectors.toList());
 
        User principal = new User(claimsForce.getSubject(), "", authorities);
 
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(principal, "", authorities);
 
        return createToken(authenticationToken);
    }
 
}