-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
1 changed file
with
60 additions
and
0 deletions.
There are no files selected for viewing
60 changes: 60 additions & 0 deletions
60
...gFirstSeminar/src/main/java/org/sopt/springFirstSeminar/common/jwt/JwtTokenGenerator.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,60 @@ | ||
package org.sopt.springFirstSeminar.common.jwt; | ||
|
||
import io.jsonwebtoken.*; | ||
import io.jsonwebtoken.security.Keys; | ||
import org.springframework.beans.factory.annotation.Value; | ||
import org.springframework.stereotype.Component; | ||
|
||
import javax.crypto.SecretKey; | ||
import java.util.Base64; | ||
import java.util.Date; | ||
|
||
@Component | ||
public class JwtTokenGenerator { | ||
|
||
@Value("${jwt.secret}") | ||
private String secretKey; | ||
|
||
@Value("${jwt.access-token-expire-time}") //1분 | ||
private long ACCESS_TOKEN_EXPIRE_TIME; | ||
|
||
@Value("${jwt.refresh-token-expire-time}") //1시간 | ||
private long REFRESH_TOKEN_EXPIRE_TIME; | ||
|
||
public String generateToken(final Long userId, boolean isAccessToken) { | ||
final Date presentDate = new Date(); | ||
final Date expireDate = generateExpireDataByToken(isAccessToken, presentDate); | ||
|
||
return Jwts.builder() | ||
.setHeaderParam(Header.TYPE, Header.JWT_TYPE) | ||
.setSubject(String.valueOf(userId)) | ||
.setIssuedAt(presentDate) | ||
.setExpiration(expireDate) | ||
.signWith(getSigningKey(), SignatureAlgorithm.HS256) //여기서 어떤 알고리즘을 사용할 지를 명시적으로 적어주는게 좋음, 안 적어주면 라이브러리 기본 설정에 의존하게됨 | ||
.compact(); | ||
} | ||
|
||
public JwtParser getJwtParser() { | ||
return Jwts.parserBuilder() | ||
.setSigningKey(getSigningKey()) | ||
.build(); | ||
} | ||
|
||
private Date generateExpireDataByToken(final boolean isAccessToken, Date presentDate) { | ||
return new Date(presentDate.getTime() + setExpireTimeByToken(isAccessToken)); | ||
} | ||
|
||
//토근에 따라 만료시간 다름 | ||
private long setExpireTimeByToken(final boolean isAccessToken) { | ||
if (isAccessToken) { | ||
return ACCESS_TOKEN_EXPIRE_TIME; | ||
} else { | ||
return REFRESH_TOKEN_EXPIRE_TIME; | ||
} | ||
} | ||
|
||
public SecretKey getSigningKey() { | ||
String encodedKey = Base64.getEncoder().encodeToString(secretKey.getBytes()); //SecretKey 통해 서명 생성 | ||
return Keys.hmacShaKeyFor(encodedKey.getBytes()); //일반적으로 HMAC (Hash-based Message Authentication Code) 알고리즘 사용 | ||
} | ||
} |