forked from FindFirst-Development/FindFirst-core
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathJwtService.java
More file actions
64 lines (51 loc) · 1.93 KB
/
JwtService.java
File metadata and controls
64 lines (51 loc) · 1.93 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
package dev.findfirst.security.jwt;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.util.Map;
import jakarta.annotation.PostConstruct;
import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServletRequest;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.Jws;
import io.jsonwebtoken.JwtParser;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.MalformedJwtException;
import io.jsonwebtoken.UnsupportedJwtException;
import io.jsonwebtoken.security.SignatureException;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.oauth2.jwt.JwtDecoder;
import org.springframework.stereotype.Service;
import org.springframework.web.util.WebUtils;
@Service
@RequiredArgsConstructor
public class JwtService {
@Value("${jwt.private.key}")
private RSAPrivateKey priv;
@Value("${jwt.public.key}")
private RSAPublicKey pubKey;
@Value("${findfirst.app.jwtCookieName}")
private String jwtCookie;
private final JwtDecoder jwtDecoder;
private JwtParser jwtParser;
@PostConstruct
private void init() {
jwtParser = Jwts.parser().verifyWith(pubKey).build();
}
public String getJwtFromCookies(HttpServletRequest request) {
Cookie cookie = WebUtils.getCookie(request, jwtCookie);
return cookie != null ? cookie.getValue() : null;
}
public Jws<Claims> parseJwt(String jwt) throws ExpiredJwtException, UnsupportedJwtException,
MalformedJwtException, SignatureException, IllegalArgumentException {
return jwtParser.parseSignedClaims(jwt);
}
public String getUserNameFromJwtToken(String token) {
return jwtDecoder.decode(token).getClaimAsString("sub");
}
public boolean validateJwtToken(String authToken) {
Map<String, Object> claims = jwtDecoder.decode(authToken).getClaims();
return claims.get("sub") != null;
}
}