forked from solid-connection/solid-connect-server
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathJwtUtils.java
More file actions
68 lines (57 loc) · 2.14 KB
/
JwtUtils.java
File metadata and controls
68 lines (57 loc) · 2.14 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
67
68
package com.example.solidconnection.util;
import com.example.solidconnection.custom.exception.CustomException;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.Jwts;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.stereotype.Component;
import java.util.Date;
import static com.example.solidconnection.custom.exception.ErrorCode.INVALID_TOKEN;
@Component
public class JwtUtils {
private static final String TOKEN_HEADER = "Authorization";
private static final String TOKEN_PREFIX = "Bearer ";
private JwtUtils() {
}
public static String parseTokenFromRequest(HttpServletRequest request) {
String token = request.getHeader(TOKEN_HEADER);
if (token == null || token.isBlank() || !token.startsWith(TOKEN_PREFIX)) {
return null;
}
return token.substring(TOKEN_PREFIX.length());
}
public static String parseSubject(String token, String secretKey) {
try {
return parseClaims(token, secretKey).getSubject();
} catch (Exception e) {
throw new CustomException(INVALID_TOKEN);
}
}
public static String parseSubjectIgnoringExpiration(String token, String secretKey) {
try {
return parseClaims(token, secretKey).getSubject();
} catch (ExpiredJwtException e) {
return e.getClaims().getSubject();
} catch (Exception e) {
throw new CustomException(INVALID_TOKEN);
}
}
public static boolean isExpired(String token, String secretKey) {
try {
Date expiration = Jwts.parser()
.setSigningKey(secretKey)
.parseClaimsJws(token)
.getBody()
.getExpiration();
return expiration.before(new Date());
} catch (Exception e) {
return true;
}
}
public static Claims parseClaims(String token, String secretKey) throws ExpiredJwtException {
return Jwts.parser()
.setSigningKey(secretKey)
.parseClaimsJws(token)
.getBody();
}
}