-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathJwtProvider.java
More file actions
71 lines (60 loc) · 2.48 KB
/
JwtProvider.java
File metadata and controls
71 lines (60 loc) · 2.48 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
69
70
71
package com.imjustdoom.pluginsite.config.security.jwt;
import com.imjustdoom.pluginsite.config.custom.JwtConfig;
import com.imjustdoom.pluginsite.model.Account;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.MalformedJwtException;
import io.jsonwebtoken.UnsupportedJwtException;
import io.jsonwebtoken.security.SignatureException;
import lombok.RequiredArgsConstructor;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Component;
import javax.servlet.http.Cookie;
import java.time.Instant;
import java.util.Date;
@Component
@RequiredArgsConstructor
public class JwtProvider {
public static final String COOKIE_NAME = "JWT-TOKEN";
private static final String USER_ID = "userId";
private final JwtConfig jwtConfig;
public Cookie generateTokenCookie(Authentication authentication) {
Cookie cookie = new Cookie(COOKIE_NAME, this.generateToken(authentication));
cookie.setSecure(this.jwtConfig.isSecureCookie());
cookie.setHttpOnly(true);
cookie.setMaxAge((int) this.jwtConfig.getExpiryTime().getSeconds());
cookie.setPath("/");
if (this.jwtConfig.getDomain() != null)
cookie.setDomain(this.jwtConfig.getDomain());
return cookie;
}
public String generateToken(Authentication authentication) {
Account account = (Account) authentication.getPrincipal();
Claims claims = Jwts.claims().setSubject(account.getUsername());
claims.put(USER_ID, account.getId());
return Jwts.builder()
.setClaims(claims)
.setIssuedAt(Date.from(Instant.now()))
.setExpiration(Date.from(Instant.now().plus(this.jwtConfig.getExpiryTime())))
.signWith(this.jwtConfig.getKey())
.compact();
}
public String getSubjectFromToken(String token) {
return Jwts.parserBuilder()
.setSigningKey(this.jwtConfig.getKey())
.build()
.parseClaimsJws(token)
.getBody().getSubject();
}
public boolean validateToken(String token) {
try {
return Jwts.parserBuilder()
.setSigningKey(this.jwtConfig.getKey())
.build()
.parseClaimsJws(token) != null;
} catch (ExpiredJwtException | UnsupportedJwtException | MalformedJwtException | SignatureException | IllegalArgumentException ex) {
return false;
}
}
}