Skip to content

jwt 로그인 구현 #3

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 7 commits into from
Mar 16, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions sample/build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -48,4 +48,6 @@ dependencies {

tasks.named('test') {
useJUnitPlatform()
// Byte Buddy 에이전트 경고 및 JVM 부트스트랩 클래스 경고 해결
// jvmArgs '-XX:+EnableDynamicAgentLoading', '-Xshare:off'
}
Original file line number Diff line number Diff line change
@@ -1,14 +1,15 @@
package com.temp.sample.config.auth;

import java.util.ArrayList;
import lombok.Getter;
import lombok.RequiredArgsConstructor;

import java.util.List;

@Getter
@RequiredArgsConstructor
public class AuthUser {
private final Long userId;

private final ArrayList<String> roles;
private final List<String> roles;

}
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@

import com.temp.sample.dao.SystemKeyRepository;
import com.temp.sample.entity.SystemKey;
import io.jsonwebtoken.JweHeader;
import io.jsonwebtoken.JwsHeader;
import io.jsonwebtoken.LocatorAdapter;
import io.jsonwebtoken.ProtectedHeader;
import io.jsonwebtoken.io.Decoders;
Expand All @@ -22,7 +24,7 @@ protected Key locate(ProtectedHeader header) {

// lookupKey(keyId) 는 키를 데이터베이스(DB), 키 저장소(Keystore), HSM(Hardware Security Module)
// 등에서 조회하는 메서드 로 직접 구현해야 한다.
//JWS 서명 검증 시, 대칭키[HMAC (HS256, HS384, HS512)]는 SecretKey를 리턴해야한다.
// JWS 서명 검증 시, 대칭키[HMAC (HS256, HS384, HS512)]는 SecretKey를 리턴해야한다.
// HSM은 provider 방식이 있음.

String keyId = header.getKeyId();
Expand All @@ -33,5 +35,4 @@ protected Key locate(ProtectedHeader header) {

}


}
98 changes: 53 additions & 45 deletions sample/src/main/java/com/temp/sample/config/auth/JwtProvider.java
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,14 @@
import com.temp.sample.dao.SystemKeyRepository;
import com.temp.sample.entity.SystemKey;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.IncorrectClaimException;
import io.jsonwebtoken.Jws;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.MissingClaimException;
import io.jsonwebtoken.Jwts.SIG;
import io.jsonwebtoken.io.Decoders;
import io.jsonwebtoken.io.Encoders;
import io.jsonwebtoken.security.Keys;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
Expand All @@ -23,62 +24,69 @@
@RequiredArgsConstructor
public class JwtProvider {

private final SystemKeyRepository systemKeyRepository;
private final JKeyLocator jKeyLocator;
private final SystemKeyRepository systemKeyRepository;
private final JKeyLocator jKeyLocator;

public static final String ISSUER = "24-mall.com";

public String createLoginToken(AuthUser authUser) {

Map<String, Object> claims = new HashMap<>();
claims.put("userId", authUser.getUserId());
claims.put("roles", authUser.getRoles());
public String createAccessToken(AuthUser authUser) {

Map<String, Object> claims = new HashMap<>();
claims.put("roles", authUser.getRoles());

SystemKey lastSecretKey = systemKeyRepository.findLastSecretKey();
SecretKey secretKey = Keys.hmacShaKeyFor(Decoders.BASE64.decode(lastSecretKey.getEncKey()));

Date now = new Date();
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Date 클래스를 쓰는게 약간 아쉽군요. 못쓸정도는 아니지만 epochTime이나 java.time 쪽 패키지를 보통 많이들 사용하긴 합니다

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

파라미터로 Date를 받아서 별생각없이 사용했는데 멘토님께서 epochTime이랑 java.time패키지를 말씀해주셔서 한번 찾아 보았습니다.

  1. jjwt는 왜 Date 타입을 사용할까?

2017년부터 Date 대신 Instant를 사용하자는 요청이 지속적으로 제기되어 왔습니다.
GitHub 이슈 PR : jwtk/jjwt#884
를 확인해 보니 0.12.x 버전까지는 Date 타입이 유지되었고, 1.0.0 버전부터 Date는 Deprecated되고 Instant 기반으로 변경될 계획이라고 합니다.

pr의 현재 문제 상황
JWT RFC 7519 표준에 따르면 NumericDate는 기본적으로 윤초를 무시한 정수로 표현 하지만 JSON에서는 비정수(소수점)을 허용하여 밀리초까지 표현할 수 있습니다.
따라서, Instant 타입을 사용할 경우 초(epoch seconds)와 밀리초(epoch millis)를 어떻게 구분할지 결정해야 합니다. 이 문제로 인해 현재 코드에는 TODO 주석이 남겨져 있으며 pr이 열려 있는 상태입니다.

todo만 빼면 다 끝난 상황인것 같은데, 그 외에도 jwtParser 문제점 개선과 맞물려 있어서 java8에 대한 지원은 빨리 적용될것 같진 않아 보입니다.

  1. EpochTime과 java.time
  • epochTime은 UTC 기준으로 경과한 시간을 초나 밀리초로 표현하여 빠른연산이 가능 합니다.
  • Date / Calendar 는 아래와 같은 문제가 있었기 때문에 java.time이 등장했고 주요 클래스로는 해당 문제들을 해결할 수 있습니다.
  1. Immutable하지 않기 때문에 스레드 세이프하지 않다.
  2. 직관적이지 않아 예측하기 힘듬 ex) 내부적으로 UTC를 사용하지만 toString 호출시 시스템 기본 시간대를 반영하여 호출
  3. 연산 시 Calendar와 함께 사용

Calendar calendar = Calendar.getInstance();
calendar.setTime(now); // 현재 시간 기준
Date expiration = calendar.getTime();
calendar.add(Calendar.MINUTE, 30);

return Jwts.builder()
.issuer(ISSUER)
.subject(String.valueOf(authUser.getUserId()))
.header().keyId("24-mall").and()
.claims(claims)
// .audience().add(audience).and()
.issuedAt(now)
.expiration(expiration)
.signWith(secretKey)
.compact();
}

SystemKey lastSecretKey = systemKeyRepository.findLastSecretKey();
SecretKey secretKey = Keys.hmacShaKeyFor(Decoders.BASE64.decode(lastSecretKey.getEncKey()));

public AuthUser readLoginToken(String token) {

return Jwts.builder()
.issuer("24-mall")
.subject("login") // sub (Subject) 클레임 설정
.header().keyId("24-mall").and() // alg, frm, zip 은 생략 가능
.claims(claims) // 주제
.audience().add("24-mall").and()
.issuedAt(new Date()) // iat (Issued At) 클레임 설정
.expiration(new Date(System.currentTimeMillis() + 3600000))
.signWith(secretKey) // 서명 설정 (기본 HS256 사용)
.id(String.valueOf(lastSecretKey.getId()))
.compact(); // 최종 JWT 생성
Jws<Claims> jws = Jwts.parser()
.clockSkewSeconds(180)
.requireSubject("login")
.requireIssuer("24-mall")
.requireAudience("24-mall")
.keyLocator(jKeyLocator)
.build()
.parseSignedClaims(token);

log.info("복호화 성공");
Claims claims = jws.getPayload();

Date expiration = claims.getExpiration();
Date now = new Date();
if(expiration.before(now)) {
throw new RuntimeException("만료된 토큰입니다.");
}

// https://web.archive.org/web/20230428094039/https://stormpath.com/blog/where-to-store-your-jwts-cookies-vs-html5-web-storage
return new AuthUser(claims.get("userId", Long.class), claims.get("roles", ArrayList.class));

}

public AuthUser readLoginToken(String token) {
// Dynamic Key Lookup(keyId) 는 키를 데이터베이스(DB), 키 저장소(Keystore), HSM(Hardware Security Module)
// 등에서 조회하는 메서드로 직접 구현할 수 있다.

try {
Jws<Claims> jws = Jwts.parser()
.clockSkewSeconds(180) // 시계오차 오차 허용 시간 설정 3분, 5분이상이면 심각한 문제 -> 생성서버와 검증서버 시간차
.requireSubject("login") // 추가 검증.
.requireIssuer("24-mall")
.requireAudience("24-mall")
.keyLocator(jKeyLocator) // 동적키
.build()
.parseSignedClaims(token); // JWT 파싱

Claims claims = jws.getPayload();
log.info("성공");

return new AuthUser(claims.get("userId", Long.class), claims.get("roles", ArrayList.class) );

} catch (Exception e){
log.error(e.getMessage());
throw new RuntimeException(e);
}

public String generateSecretKey() {
SecretKey secretKey = SIG.HS256.key().build();

return Encoders.BASE64.encode(secretKey.getEncoded());
}


}
Original file line number Diff line number Diff line change
Expand Up @@ -27,11 +27,12 @@ public class JwtFilter extends OncePerRequestFilter {
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response,
FilterChain filterChain) throws ServletException, IOException {

if(!request.getRequestURL().toString().endsWith("login")){
// 로그인 요청이 아니면 authorization 검사
if (!request.getRequestURL().toString().endsWith("login")) {

String token = request.getHeader("Authorization");

if (StringUtils.isEmpty(token)){
if (StringUtils.isEmpty(token)) {
throw new RuntimeException("Token is empty");
}

Expand All @@ -44,6 +45,4 @@ protected void doFilterInternal(HttpServletRequest request, HttpServletResponse

}



}
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

import com.temp.sample.service.ProductService;
import com.temp.sample.service.request.ProductRequest;
import jakarta.servlet.http.HttpServletRequest;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
Expand All @@ -12,14 +13,17 @@
@RequiredArgsConstructor
public class ProductController {

private final ProductService productService;
private final ProductService productService;

@PostMapping("/products")
ApiResponse getProducts(@RequestBody ProductRequest request){
@PostMapping("/products")
ApiResponse getProducts(@RequestBody ProductRequest request, HttpServletRequest httpRequest) {

productService.read(request.getId());
// 필터에서 설정된 속성 가져오기
Long userId = (Long) httpRequest.getAttribute("userId");

return ApiResponse.OK;
}
productService.read(request.getId());

return ApiResponse.OK;
}

}
15 changes: 11 additions & 4 deletions sample/src/main/java/com/temp/sample/entity/SystemKey.java
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,8 @@
import jakarta.persistence.Id;
import jakarta.persistence.Table;
import java.time.LocalDateTime;
import lombok.AccessLevel;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.ToString;

import lombok.*;

@Table(name = "system_key")
@Getter
Expand All @@ -26,4 +24,13 @@ public class SystemKey {
private Boolean isActive;


public static SystemKey create(Long id, String encKey, LocalDateTime createdAt, Boolean isActive) {
SystemKey systemKey = new SystemKey();
systemKey.id = id;
systemKey.encKey = encKey;
systemKey.createdAt = createdAt;
systemKey.isActive = isActive;
return systemKey;
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@
import com.temp.sample.dao.UserRepository;
import com.temp.sample.entity.User;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.StringUtils;
Expand All @@ -28,7 +27,10 @@ public String login(LoginReq req) {
AuthUser authUser = new AuthUser(user.getId(),
new ArrayList<>(List.of("bronze", "silver", "gold")));

String loginToken = jwtProvider.createLoginToken(authUser);
// todo 사용자 등급별 접속가능 경로 설정
// String audience = "/premium";

String loginToken = jwtProvider.createAccessToken(authUser);

return loginToken;
}
Expand Down
Loading
Loading