Skip to content

Commit

Permalink
[Chore] 잘못된 파일 수정 변경(#13)
Browse files Browse the repository at this point in the history
  • Loading branch information
sjk4618 committed Jun 2, 2024
1 parent faa1ea4 commit b62dd35
Showing 1 changed file with 60 additions and 0 deletions.
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) 알고리즘 사용
}
}

0 comments on commit b62dd35

Please sign in to comment.