From d67ec2230bd1ca3e6982f4a97d82b3970173f0c7 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 30 Nov 2026 17:14:31 +0900 Subject: [PATCH 1/3] =?UTF-8?q?fix:=20refresh=20=ED=86=A0=ED=81=B0?= =?UTF-8?q?=EC=9C=BC=EB=A1=9C=20API=20=EC=9D=B8=EC=A6=9D=EC=9D=84=20?= =?UTF-8?q?=ED=95=A0=20=EC=88=98=20=EC=97=86=EA=B2=8C=20=ED=95=9C=EB=8B=A4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit access/refresh 토큰에 tokenType claim(access, refresh)을 넣고, 사용자·admin JWT 필터는 refresh로 명시된 토큰을 유효하지 않은 토큰으로 처리한다. 재발급(AuthService.reissue, AdminAuthService.refresh)은 access로 명시된 토큰을 INVALID_REFRESH_TOKEN으로 거부한다. 배포 전에 발급된 claim 없는 토큰은 access·refresh 양쪽에서 기존처럼 허용한다. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01DNr3PM1DZCQLC8RiGJwD3a --- .../jwt/JwtAuthenticationFilterTest.java | 136 ++++++++++++++++++ .../JwtTokenTypeIntegrationTest.java | 128 +++++++++++++++++ .../user/service/AuthServiceTest.java | 66 ++++++++- .../AdminApiSecurityIntegrationTest.java | 19 +++ .../security/constant/JwtTokenType.java | 26 ++++ .../jwt/AdminJwtAuthenticationFilter.java | 2 +- .../security/jwt/JwtAuthenticationFilter.java | 2 +- .../global/security/jwt/JwtTokenProvider.java | 18 ++- .../security/jwt/JwtTokenValidator.java | 23 ++- .../user/service/AdminAuthService.java | 4 +- .../bottlenote/user/service/AuthService.java | 3 +- .../jwt/AdminJwtAuthenticationFilterTest.java | 135 +++++++++++++++++ .../security/jwt/JwtTokenValidatorTest.java | 129 +++++++++++++++++ .../user/service/AdminAuthServiceTest.java | 78 +++++++++- 14 files changed, 750 insertions(+), 19 deletions(-) create mode 100644 bottlenote-api/src/test/java/app/bottlenote/global/security/jwt/JwtAuthenticationFilterTest.java create mode 100644 bottlenote-api/src/test/java/app/bottlenote/user/integration/JwtTokenTypeIntegrationTest.java create mode 100644 module-domains/user/src/main/java/app/bottlenote/global/security/constant/JwtTokenType.java create mode 100644 module-domains/user/src/test/java/app/bottlenote/global/security/jwt/AdminJwtAuthenticationFilterTest.java create mode 100644 module-domains/user/src/test/java/app/bottlenote/global/security/jwt/JwtTokenValidatorTest.java diff --git a/bottlenote-api/src/test/java/app/bottlenote/global/security/jwt/JwtAuthenticationFilterTest.java b/bottlenote-api/src/test/java/app/bottlenote/global/security/jwt/JwtAuthenticationFilterTest.java new file mode 100644 index 000000000..ad9897165 --- /dev/null +++ b/bottlenote-api/src/test/java/app/bottlenote/global/security/jwt/JwtAuthenticationFilterTest.java @@ -0,0 +1,136 @@ +package app.bottlenote.global.security.jwt; + +import static app.bottlenote.global.annotation.SecurityPolicy.AuthType.REQUIRED_AUTH; +import static org.assertj.core.api.Assertions.assertThat; + +import app.bottlenote.global.security.CustomUserDetailsService; +import app.bottlenote.global.security.policy.SecurityPolicyRegistry; +import app.bottlenote.global.security.policy.SecurityPolicyRoute; +import app.bottlenote.user.constant.SocialType; +import app.bottlenote.user.constant.UserType; +import app.bottlenote.user.domain.User; +import app.bottlenote.user.fake.FakeOauthRepository; +import io.jsonwebtoken.Jwts; +import io.jsonwebtoken.MalformedJwtException; +import io.jsonwebtoken.SignatureAlgorithm; +import io.jsonwebtoken.io.Decoders; +import io.jsonwebtoken.security.Keys; +import java.util.ArrayList; +import java.util.Date; +import java.util.List; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; +import org.springframework.mock.web.MockFilterChain; +import org.springframework.mock.web.MockHttpServletRequest; +import org.springframework.mock.web.MockHttpServletResponse; +import org.springframework.security.core.context.SecurityContextHolder; + +@Tag("unit") +@DisplayName("[unit] product JWT 필터의 토큰 판정") +class JwtAuthenticationFilterTest { + + private static final String TEST_JWT_SECRET = + "dGVzdC1zZWNyZXQta2V5LWZvci1qd3QtdG9rZW4tZ2VuZXJhdGlvbi10ZXN0aW5nLXB1cnBvc2UtbG9uZy1lbm91Z2gtZm9yLWhtYWMtc2hhLTUxMi12ZXJzaW9uLWFuZC1pbXBvcnRhbnQtc2VjdXJpdHktaW4tbW9kZXJuLWphdmEtYXBwbGljYXRpb25z"; + private static final String REQUIRED_PATH = "/api/v1/likes"; + + private final JwtTokenProvider tokenProvider = new JwtTokenProvider(TEST_JWT_SECRET); + private FakeOauthRepository oauthRepository; + private JwtAuthenticationFilter filter; + private User user; + + @BeforeEach + void setUp() { + new JwtTokenValidator(TEST_JWT_SECRET); + oauthRepository = new FakeOauthRepository(); + SecurityPolicyRegistry policyRegistry = + new SecurityPolicyRegistry( + List.of(SecurityPolicyRoute.explicit("PUT", REQUIRED_PATH, REQUIRED_AUTH))); + filter = + new JwtAuthenticationFilter( + new JwtAuthenticationManager( + TEST_JWT_SECRET, new CustomUserDetailsService(oauthRepository)), + policyRegistry); + user = oauthRepository.save(user("user@bottlenote.com")); + } + + @AfterEach + void tearDown() { + SecurityContextHolder.clearContext(); + } + + @Test + @DisplayName("access 토큰으로 요청할 때 인증 컨텍스트를 설정한다") + void accessToken_authenticates() throws Exception { + // given + String accessToken = + tokenProvider.createAccessToken(user.getEmail(), user.getRole(), user.getId()); + + // when + MockHttpServletRequest request = filter(accessToken); + + // then + assertThat(request.getAttribute("exception")).isNull(); + assertThat(SecurityContextHolder.getContext().getAuthentication()).isNotNull(); + } + + @Test + @DisplayName("refresh 토큰을 Bearer로 요청할 때 유효하지 않은 토큰으로 처리하고 인증하지 않는다") + void refreshToken_isRejected() throws Exception { + // given + String refreshToken = + tokenProvider.createRefreshToken(user.getEmail(), user.getRole(), user.getId()); + + // when + MockHttpServletRequest request = filter(refreshToken); + + // then + assertThat(request.getAttribute("exception")).isInstanceOf(MalformedJwtException.class); + assertThat(SecurityContextHolder.getContext().getAuthentication()).isNull(); + } + + @Test + @DisplayName("tokenType claim이 없는 배포 전 토큰으로 요청할 때 기존처럼 인증한다") + void legacyToken_authenticates() throws Exception { + // given + String legacyToken = legacyToken(user.getEmail()); + + // when + MockHttpServletRequest request = filter(legacyToken); + + // then + assertThat(request.getAttribute("exception")).isNull(); + assertThat(SecurityContextHolder.getContext().getAuthentication()).isNotNull(); + } + + private MockHttpServletRequest filter(String token) throws Exception { + MockHttpServletRequest request = new MockHttpServletRequest("PUT", REQUIRED_PATH); + request.addHeader("Authorization", "Bearer " + token); + filter.doFilter(request, new MockHttpServletResponse(), new MockFilterChain()); + return request; + } + + private static User user(String email) { + return User.builder() + .email(email) + .nickName(email) + .socialType(new ArrayList<>(List.of(SocialType.KAKAO))) + .role(UserType.ROLE_USER) + .build(); + } + + private static String legacyToken(String email) { + Date now = new Date(); + return Jwts.builder() + .setSubject(email) + .claim(JwtTokenProvider.KEY_ROLES, UserType.ROLE_USER.name()) + .claim("userId", 1L) + .setIssuedAt(now) + .setExpiration(new Date(now.getTime() + 60_000)) + .signWith( + Keys.hmacShaKeyFor(Decoders.BASE64.decode(TEST_JWT_SECRET)), SignatureAlgorithm.HS512) + .compact(); + } +} diff --git a/bottlenote-api/src/test/java/app/bottlenote/user/integration/JwtTokenTypeIntegrationTest.java b/bottlenote-api/src/test/java/app/bottlenote/user/integration/JwtTokenTypeIntegrationTest.java new file mode 100644 index 000000000..dab6f4372 --- /dev/null +++ b/bottlenote-api/src/test/java/app/bottlenote/user/integration/JwtTokenTypeIntegrationTest.java @@ -0,0 +1,128 @@ +package app.bottlenote.user.integration; + +import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.csrf; + +import app.bottlenote.IntegrationTestSupport; +import app.bottlenote.global.security.jwt.JwtTokenProvider; +import app.bottlenote.user.domain.User; +import app.bottlenote.user.dto.response.TokenItem; +import app.bottlenote.user.fixture.UserTestFactory; +import io.jsonwebtoken.Jwts; +import io.jsonwebtoken.SignatureAlgorithm; +import io.jsonwebtoken.io.Decoders; +import io.jsonwebtoken.security.Keys; +import java.util.Date; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.http.HttpStatus; +import org.springframework.test.web.servlet.assertj.MvcTestResult; + +@Tag("integration") +@DisplayName("[integration] JWT 토큰 종류에 따른 인증과 재발급") +class JwtTokenTypeIntegrationTest extends IntegrationTestSupport { + + private static final String PROTECTED_URI = "/api/v1/users/current"; + private static final String REISSUE_URI = "/api/v2/auth/reissue"; + + @Autowired private UserTestFactory userTestFactory; + + @Value("${security.jwt.secret-key}") + private String secretKey; + + @Test + @DisplayName("access 토큰으로 인증 필수 API를 호출할 때 200을 반환한다") + void access_토큰으로_인증_필수_API를_호출할_수_있다() { + // given + TokenItem token = getToken(userTestFactory.persistUser()); + + // when + MvcTestResult result = callProtected(token.accessToken()); + + // then + result.assertThat().hasStatusOk(); + } + + @Test + @DisplayName("refresh 토큰을 Bearer로 인증 필수 API를 호출할 때 401을 반환한다") + void refresh_토큰으로_인증_필수_API를_호출할_수_없다() { + // given + TokenItem token = getToken(userTestFactory.persistUser()); + + // when + MvcTestResult result = callProtected(token.refreshToken()); + + // then + result.assertThat().hasStatus(HttpStatus.UNAUTHORIZED); + } + + @Test + @DisplayName("tokenType claim이 없는 배포 전 토큰으로 인증 필수 API를 호출할 때 200을 반환한다") + void 배포_전_토큰으로_인증_필수_API를_호출할_수_있다() { + // given + User user = userTestFactory.persistUser(); + + // when + MvcTestResult result = callProtected(legacyToken(user)); + + // then + result.assertThat().hasStatusOk(); + } + + @Test + @DisplayName("refresh 토큰으로 재발급을 요청할 때 200을 반환한다") + void refresh_토큰으로_재발급할_수_있다() { + // given + TokenItem token = getToken(userTestFactory.persistUser()); + + // when + MvcTestResult result = reissue(token.refreshToken()); + + // then + result.assertThat().hasStatusOk(); + } + + @Test + @DisplayName("access 토큰으로 재발급을 요청할 때 401을 반환한다") + void access_토큰으로_재발급할_수_없다() { + // given + TokenItem token = getToken(userTestFactory.persistUser()); + + // when + MvcTestResult result = reissue(token.accessToken()); + + // then + result.assertThat().hasStatus(HttpStatus.UNAUTHORIZED); + } + + private MvcTestResult callProtected(String token) { + return mockMvcTester + .get() + .uri(PROTECTED_URI) + .header("Authorization", "Bearer " + token) + .exchange(); + } + + private MvcTestResult reissue(String token) { + return mockMvcTester + .post() + .uri(REISSUE_URI) + .header("refresh-token", token) + .with(csrf()) + .exchange(); + } + + private String legacyToken(User user) { + Date now = new Date(); + return Jwts.builder() + .setSubject(user.getEmail()) + .claim(JwtTokenProvider.KEY_ROLES, user.getRole().name()) + .claim("userId", user.getId()) + .setIssuedAt(now) + .setExpiration(new Date(now.getTime() + 60_000)) + .signWith(Keys.hmacShaKeyFor(Decoders.BASE64.decode(secretKey)), SignatureAlgorithm.HS512) + .compact(); + } +} diff --git a/bottlenote-api/src/test/java/app/bottlenote/user/service/AuthServiceTest.java b/bottlenote-api/src/test/java/app/bottlenote/user/service/AuthServiceTest.java index 5f2adbf9c..9a320b61a 100644 --- a/bottlenote-api/src/test/java/app/bottlenote/user/service/AuthServiceTest.java +++ b/bottlenote-api/src/test/java/app/bottlenote/user/service/AuthServiceTest.java @@ -20,6 +20,7 @@ import app.bottlenote.agreement.fixture.InMemoryUserAgreementRepository; import app.bottlenote.agreement.service.AgreementEvaluator; import app.bottlenote.agreement.service.DefaultAgreementFacade; +import app.bottlenote.global.security.jwt.JwtTokenProvider; import app.bottlenote.global.security.jwt.JwtTokenValidator; import app.bottlenote.user.constant.GenderType; import app.bottlenote.user.constant.SocialType; @@ -33,12 +34,15 @@ import app.bottlenote.user.fake.FakeJwtTokenProvider; import app.bottlenote.user.fake.FakeOauthRepository; import app.bottlenote.user.repository.RootAdminRepository; +import io.jsonwebtoken.Jwts; +import io.jsonwebtoken.SignatureAlgorithm; import io.jsonwebtoken.io.Decoders; import io.jsonwebtoken.security.Keys; import java.lang.reflect.Field; import java.security.Key; import java.time.LocalDateTime; import java.util.ArrayList; +import java.util.Date; import java.util.List; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.DisplayName; @@ -49,6 +53,9 @@ @DisplayName("[unit] [service] AuthService") class AuthServiceTest { + private static final String TEST_JWT_SECRET = + "dGVzdC1zZWNyZXQta2V5LWZvci1qd3QtdG9rZW4tZ2VuZXJhdGlvbi10ZXN0aW5nLXB1cnBvc2UtbG9uZy1lbm91Z2gtZm9yLWhtYWMtc2hhLTUxMi12ZXJzaW9uLWFuZC1pbXBvcnRhbnQtc2VjdXJpdHktaW4tbW9kZXJuLWphdmEtYXBwbGljYXRpb25z"; + private static String apiKey(char value) { return "bn_agent_" + String.valueOf(value).repeat(43); } @@ -93,9 +100,7 @@ void setUp() throws Exception { } private void initializeJwtTokenValidator() throws Exception { - String secret = - "dGVzdC1zZWNyZXQta2V5LWZvci1qd3QtdG9rZW4tZ2VuZXJhdGlvbi10ZXN0aW5nLXB1cnBvc2UtbG9uZy1lbm91Z2gtZm9yLWhtYWMtc2hhLTUxMi12ZXJzaW9uLWFuZC1pbXBvcnRhbnQtc2VjdXJpdHktaW4tbW9kZXJuLWphdmEtYXBwbGljYXRpb25z"; - byte[] keyBytes = Decoders.BASE64.decode(secret); + byte[] keyBytes = Decoders.BASE64.decode(TEST_JWT_SECRET); Key secretKey = Keys.hmacShaKeyFor(keyBytes); Field secretKeyField = JwtTokenValidator.class.getDeclaredField("secretKey"); @@ -397,6 +402,38 @@ void reissue_token() { assertThat(response.refreshToken()).isNotNull().isNotEmpty(); } + @Test + @DisplayName("tokenType claim이 없는 배포 전 refresh 토큰으로 재발급을 요청할 때 새 토큰을 발급한다") + void reissue_withLegacyRefreshToken_reissues() { + // given + String legacyRefreshToken = legacyToken("legacy@bottlenote.com"); + oauthRepository.save(userWithRefreshToken("legacy@bottlenote.com", legacyRefreshToken)); + + // when + TokenItem response = authService.reissue(legacyRefreshToken); + + // then + assertThat(response.accessToken()).isNotBlank(); + assertThat(response.refreshToken()).isNotBlank(); + } + + @Test + @DisplayName("access 종류로 명시된 토큰으로 재발급을 요청할 때 INVALID_REFRESH_TOKEN 예외가 발생한다") + void reissue_withAccessToken_throwsInvalidRefreshToken() { + // given + String accessToken = + jwtTokenProvider.createAccessToken("access@bottlenote.com", UserType.ROLE_USER, 1L); + // 저장소 조회가 통과하더라도 토큰 종류 검사로 거부되는지 확인한다 + oauthRepository.save(userWithRefreshToken("access@bottlenote.com", accessToken)); + + // when + UserException exception = + assertThrows(UserException.class, () -> authService.reissue(accessToken)); + + // then + assertThat(exception.getExceptionCode()).isEqualTo(UserExceptionCode.INVALID_REFRESH_TOKEN); + } + @Test @DisplayName("토큰 검증에 통과하지 못하면 토큰 재발급에 실패한다") void reissue_token_fail() { @@ -550,6 +587,29 @@ void loginWithAgent_withdrawnUser_throwsAuthenticationFailed() { .isEqualTo(UserExceptionCode.AGENT_AUTHENTICATION_FAILED); } + private User userWithRefreshToken(String email, String refreshToken) { + return User.builder() + .email(email) + .nickName(email) + .socialType(new ArrayList<>(List.of(SocialType.KAKAO))) + .role(UserType.ROLE_USER) + .refreshToken(refreshToken) + .build(); + } + + private String legacyToken(String email) { + Date now = new Date(); + return Jwts.builder() + .setSubject(email) + .claim(JwtTokenProvider.KEY_ROLES, UserType.ROLE_USER.name()) + .claim("userId", 1L) + .setIssuedAt(now) + .setExpiration(new Date(now.getTime() + 60_000)) + .signWith( + Keys.hmacShaKeyFor(Decoders.BASE64.decode(TEST_JWT_SECRET)), SignatureAlgorithm.HS512) + .compact(); + } + private Field getLastLoginAtField() { try { Field field = User.class.getDeclaredField("lastLoginAt"); diff --git a/bottlenote-api/src/test/java/app/global/admin/AdminApiSecurityIntegrationTest.java b/bottlenote-api/src/test/java/app/global/admin/AdminApiSecurityIntegrationTest.java index ce339114b..dbdfafc1d 100644 --- a/bottlenote-api/src/test/java/app/global/admin/AdminApiSecurityIntegrationTest.java +++ b/bottlenote-api/src/test/java/app/global/admin/AdminApiSecurityIntegrationTest.java @@ -98,6 +98,25 @@ class AdminApiSecurityIntegrationTest extends AdminApiIntegrationTestSupport { assertThat(violations).isEmpty(); } + @Test + @DisplayName("admin refresh 토큰을 Bearer로 인증 필수 admin 라우트를 호출할 때 403으로 거부한다") + void admin_refresh_토큰은_거부된다() throws Exception { + AdminUser admin = adminUserTestFactory.persistRootAdmin(); + String refreshToken = + jwtTokenProvider + .generateAdminToken(admin.getEmail(), admin.getRoles(), admin.getId()) + .refreshToken(); + List violations = new ArrayList<>(); + for (AdminRoute route : adminRoutes()) { + if (route.auth() != AuthType.REQUIRED_AUTH) { + continue; + } + checkRejection(route, call(route, refreshToken), true, violations); + } + + assertThat(violations).isEmpty(); + } + @Test @DisplayName("admin 토큰으로 admin 라우트를 호출할 때 모든 라우트가 보안 체인을 통과한다") void admin_토큰은_모든_admin_라우트를_통과한다() throws Exception { diff --git a/module-domains/user/src/main/java/app/bottlenote/global/security/constant/JwtTokenType.java b/module-domains/user/src/main/java/app/bottlenote/global/security/constant/JwtTokenType.java new file mode 100644 index 000000000..cb37ce4dc --- /dev/null +++ b/module-domains/user/src/main/java/app/bottlenote/global/security/constant/JwtTokenType.java @@ -0,0 +1,26 @@ +package app.bottlenote.global.security.constant; + +import io.jsonwebtoken.Claims; + +/** JWT의 용도를 구분하는 tokenType claim 값 */ +public enum JwtTokenType { + ACCESS("access"), + REFRESH("refresh"); + + public static final String CLAIM_NAME = "tokenType"; + + private final String value; + + JwtTokenType(String value) { + this.value = value; + } + + public String getValue() { + return value; + } + + /** claim에 이 종류가 명시되어 있으면 true를 반환한다 */ + public boolean isDeclaredIn(Claims claims) { + return value.equals(claims.get(CLAIM_NAME)); + } +} diff --git a/module-domains/user/src/main/java/app/bottlenote/global/security/jwt/AdminJwtAuthenticationFilter.java b/module-domains/user/src/main/java/app/bottlenote/global/security/jwt/AdminJwtAuthenticationFilter.java index 2c5d5fc67..9c32afc41 100644 --- a/module-domains/user/src/main/java/app/bottlenote/global/security/jwt/AdminJwtAuthenticationFilter.java +++ b/module-domains/user/src/main/java/app/bottlenote/global/security/jwt/AdminJwtAuthenticationFilter.java @@ -80,7 +80,7 @@ protected void doFilterInternal( return; } - if (!JwtTokenValidator.validateToken(token)) { + if (!JwtTokenValidator.validateAccessToken(token)) { log.warn("유효하지 않은 Admin 토큰입니다."); request.setAttribute("exception", new MalformedJwtException("토큰이 유효하지 않습니다.")); filterChain.doFilter(request, response); diff --git a/module-domains/user/src/main/java/app/bottlenote/global/security/jwt/JwtAuthenticationFilter.java b/module-domains/user/src/main/java/app/bottlenote/global/security/jwt/JwtAuthenticationFilter.java index 8fd651e87..93ee7b80b 100644 --- a/module-domains/user/src/main/java/app/bottlenote/global/security/jwt/JwtAuthenticationFilter.java +++ b/module-domains/user/src/main/java/app/bottlenote/global/security/jwt/JwtAuthenticationFilter.java @@ -58,7 +58,7 @@ protected void doFilterInternal( if (MaliciousPathPattern.matches(request)) { authentication = jwtAuthenticationManager.getAnonymousAuthentication(); } else if (token != null && !token.isBlank()) { - if (!JwtTokenValidator.validateToken(token)) { + if (!JwtTokenValidator.validateAccessToken(token)) { log.info("MalformedJwtException : 토큰이 유효하지 않습니다."); request.setAttribute("exception", new MalformedJwtException("토큰이 유효하지 않습니다.")); filterChain.doFilter(request, response); diff --git a/module-domains/user/src/main/java/app/bottlenote/global/security/jwt/JwtTokenProvider.java b/module-domains/user/src/main/java/app/bottlenote/global/security/jwt/JwtTokenProvider.java index c0736b622..8e18fb860 100644 --- a/module-domains/user/src/main/java/app/bottlenote/global/security/jwt/JwtTokenProvider.java +++ b/module-domains/user/src/main/java/app/bottlenote/global/security/jwt/JwtTokenProvider.java @@ -1,5 +1,6 @@ package app.bottlenote.global.security.jwt; +import app.bottlenote.global.security.constant.JwtTokenType; import app.bottlenote.user.constant.AdminRole; import app.bottlenote.user.constant.UserType; import app.bottlenote.user.dto.response.TokenItem; @@ -58,7 +59,7 @@ public TokenItem generateToken(String userEmail, UserType role, Long userId) { * @return access token ( 엑세스 토큰 ) */ public String createAccessToken(String userEmail, UserType role, Long userId) { - Claims claims = createClaims(userEmail, role, userId); + Claims claims = createClaims(userEmail, role, userId, JwtTokenType.ACCESS); Date now = new Date(); return Jwts.builder() .setClaims(claims) @@ -77,7 +78,7 @@ public String createAccessToken(String userEmail, UserType role, Long userId) { * @return refresh token ( 리프레시 토큰 ) */ public String createRefreshToken(String userEmail, UserType role, Long userId) { - Claims claims = createClaims(userEmail, role, userId); + Claims claims = createClaims(userEmail, role, userId, JwtTokenType.REFRESH); Date now = new Date(); return Jwts.builder() .setClaims(claims) @@ -93,12 +94,15 @@ public String createRefreshToken(String userEmail, UserType role, Long userId) { * @param userEmail 토큰 생성용 유저 이메일 * @param role 유저의 권한 * @param userId 유저 고유 아이디 + * @param tokenType 토큰 용도 ( access, refresh ) * @return 클레임 객체 ( 토큰에 담을 정보 ) */ - private Claims createClaims(String userEmail, UserType role, Long userId) { + private Claims createClaims( + String userEmail, UserType role, Long userId, JwtTokenType tokenType) { Claims claims = Jwts.claims().setSubject(userEmail); claims.put(KEY_ROLES, role.name()); claims.put("userId", userId); + claims.put(JwtTokenType.CLAIM_NAME, tokenType.getValue()); return claims; } @@ -110,7 +114,7 @@ public TokenItem generateAdminToken(String email, List roles, Long ad } public String createAdminAccessToken(String email, List roles, Long adminId) { - Claims claims = createAdminClaims(email, roles, adminId); + Claims claims = createAdminClaims(email, roles, adminId, JwtTokenType.ACCESS); Date now = new Date(); return Jwts.builder() .setClaims(claims) @@ -121,7 +125,7 @@ public String createAdminAccessToken(String email, List roles, Long a } public String createAdminRefreshToken(String email, List roles, Long adminId) { - Claims claims = createAdminClaims(email, roles, adminId); + Claims claims = createAdminClaims(email, roles, adminId, JwtTokenType.REFRESH); Date now = new Date(); return Jwts.builder() .setClaims(claims) @@ -131,12 +135,14 @@ public String createAdminRefreshToken(String email, List roles, Long .compact(); } - private Claims createAdminClaims(String email, List roles, Long adminId) { + private Claims createAdminClaims( + String email, List roles, Long adminId, JwtTokenType tokenType) { Claims claims = Jwts.claims().setSubject(email); String rolesString = roles.stream().map(AdminRole::name).collect(Collectors.joining(",")); claims.put(KEY_ROLES, rolesString); claims.put("userId", adminId); claims.put("isAdmin", true); + claims.put(JwtTokenType.CLAIM_NAME, tokenType.getValue()); return claims; } } diff --git a/module-domains/user/src/main/java/app/bottlenote/global/security/jwt/JwtTokenValidator.java b/module-domains/user/src/main/java/app/bottlenote/global/security/jwt/JwtTokenValidator.java index c7d7bfbea..fa55b37b3 100644 --- a/module-domains/user/src/main/java/app/bottlenote/global/security/jwt/JwtTokenValidator.java +++ b/module-domains/user/src/main/java/app/bottlenote/global/security/jwt/JwtTokenValidator.java @@ -1,5 +1,7 @@ package app.bottlenote.global.security.jwt; +import app.bottlenote.global.security.constant.JwtTokenType; +import io.jsonwebtoken.Claims; import io.jsonwebtoken.ExpiredJwtException; import io.jsonwebtoken.Jwts; import io.jsonwebtoken.MalformedJwtException; @@ -30,14 +32,27 @@ public static boolean validateToken(String token) UnsupportedJwtException, IllegalArgumentException, CustomJwtException { + parseClaims(token); + return true; + } + /** Bearer 인증에 쓸 수 있는 토큰인지 검사한다. refresh 용도로 명시된 토큰은 false를 반환한다. */ + public static boolean validateAccessToken(String token) { + // tokenType claim이 없는 배포 전 토큰은 access로 받아들인다(배포 즉시 전원 로그아웃 방지, 최대 14일 뒤 모두 만료) + return !JwtTokenType.REFRESH.isDeclaredIn(parseClaims(token)); + } + + /** 재발급에 쓸 수 있는 토큰인지 검사한다. access 용도로 명시된 토큰은 false를 반환한다. */ + public static boolean validateRefreshToken(String token) { + // tokenType claim이 없는 배포 전 refresh token도 재발급을 허용한다 + return !JwtTokenType.ACCESS.isDeclaredIn(parseClaims(token)); + } + + private static Claims parseClaims(String token) { if (token == null || token.trim().isEmpty()) { log.warn("토큰이 존재하지 않습니다."); throw new CustomJwtException(CustomJwtExceptionCode.EMPTY_JWT_TOKEN); } - - Jwts.parserBuilder().setSigningKey(secretKey).build().parseClaimsJws(token); - - return true; + return Jwts.parserBuilder().setSigningKey(secretKey).build().parseClaimsJws(token).getBody(); } } diff --git a/module-domains/user/src/main/java/app/bottlenote/user/service/AdminAuthService.java b/module-domains/user/src/main/java/app/bottlenote/user/service/AdminAuthService.java index f5baeda34..821cdb58b 100644 --- a/module-domains/user/src/main/java/app/bottlenote/user/service/AdminAuthService.java +++ b/module-domains/user/src/main/java/app/bottlenote/user/service/AdminAuthService.java @@ -1,6 +1,6 @@ package app.bottlenote.user.service; -import static app.bottlenote.global.security.jwt.JwtTokenValidator.validateToken; +import static app.bottlenote.global.security.jwt.JwtTokenValidator.validateRefreshToken; import static app.bottlenote.user.exception.UserExceptionCode.AGENT_AUTHENTICATION_FAILED; import static app.bottlenote.user.exception.UserExceptionCode.AGENT_KEY_INVALID_FORMAT; import static app.bottlenote.user.exception.UserExceptionCode.INVALID_REFRESH_TOKEN; @@ -94,7 +94,7 @@ public TokenItem loginWithAgent(String rawAgentKey) { @Transactional public TokenItem refresh(String refreshToken) { try { - if (!validateToken(refreshToken)) { + if (!validateRefreshToken(refreshToken)) { throw new UserException(INVALID_REFRESH_TOKEN); } } catch (UserException e) { diff --git a/module-domains/user/src/main/java/app/bottlenote/user/service/AuthService.java b/module-domains/user/src/main/java/app/bottlenote/user/service/AuthService.java index 8935ca235..54bfe9ef8 100644 --- a/module-domains/user/src/main/java/app/bottlenote/user/service/AuthService.java +++ b/module-domains/user/src/main/java/app/bottlenote/user/service/AuthService.java @@ -1,5 +1,6 @@ package app.bottlenote.user.service; +import static app.bottlenote.global.security.jwt.JwtTokenValidator.validateRefreshToken; import static app.bottlenote.global.security.jwt.JwtTokenValidator.validateToken; import static app.bottlenote.user.exception.UserExceptionCode.AGENT_AUTHENTICATION_FAILED; import static app.bottlenote.user.exception.UserExceptionCode.AGENT_KEY_INVALID_FORMAT; @@ -112,7 +113,7 @@ public AuthResponse loginWithAgent(String rawAgentKey) { @Transactional public TokenItem reissue(String refreshToken) { try { - if (!validateToken(refreshToken)) { + if (!validateRefreshToken(refreshToken)) { throw new UserException(INVALID_REFRESH_TOKEN); } } catch (Exception e) { diff --git a/module-domains/user/src/test/java/app/bottlenote/global/security/jwt/AdminJwtAuthenticationFilterTest.java b/module-domains/user/src/test/java/app/bottlenote/global/security/jwt/AdminJwtAuthenticationFilterTest.java new file mode 100644 index 000000000..32d41abb6 --- /dev/null +++ b/module-domains/user/src/test/java/app/bottlenote/global/security/jwt/AdminJwtAuthenticationFilterTest.java @@ -0,0 +1,135 @@ +package app.bottlenote.global.security.jwt; + +import static app.bottlenote.global.annotation.SecurityPolicy.AuthType.REQUIRED_AUTH; +import static org.assertj.core.api.Assertions.assertThat; + +import app.bottlenote.global.security.CustomAdminUserDetailsService; +import app.bottlenote.global.security.constant.MaliciousPathPattern; +import app.bottlenote.global.security.policy.SecurityPolicyRegistry; +import app.bottlenote.global.security.policy.SecurityPolicyRoute; +import app.bottlenote.user.constant.AdminRole; +import app.bottlenote.user.constant.UserStatus; +import app.bottlenote.user.domain.AdminUser; +import app.bottlenote.user.fixture.InMemoryAdminUserRepository; +import io.jsonwebtoken.Jwts; +import io.jsonwebtoken.MalformedJwtException; +import io.jsonwebtoken.SignatureAlgorithm; +import io.jsonwebtoken.io.Decoders; +import io.jsonwebtoken.security.Keys; +import java.util.Date; +import java.util.List; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; +import org.springframework.mock.web.MockFilterChain; +import org.springframework.mock.web.MockHttpServletRequest; +import org.springframework.mock.web.MockHttpServletResponse; +import org.springframework.security.core.context.SecurityContextHolder; + +@Tag("unit") +@DisplayName("[unit] admin JWT 필터의 토큰 종류 판정") +class AdminJwtAuthenticationFilterTest { + + private static final String TEST_JWT_SECRET = + "dGVzdC1zZWNyZXQta2V5LWZvci1qd3QtdG9rZW4tZ2VuZXJhdGlvbi10ZXN0aW5nLXB1cnBvc2UtbG9uZy1lbm91Z2gtZm9yLWhtYWMtc2hhLTUxMi12ZXJzaW9uLWFuZC1pbXBvcnRhbnQtc2VjdXJpdHktaW4tbW9kZXJuLWphdmEtYXBwbGljYXRpb25z"; + private static final String REQUIRED_PATH = "/admin/api/v1/users"; + + private final JwtTokenProvider tokenProvider = new JwtTokenProvider(TEST_JWT_SECRET); + private InMemoryAdminUserRepository adminUserRepository; + private AdminJwtAuthenticationFilter filter; + private AdminUser admin; + + @BeforeEach + void setUp() { + new JwtTokenValidator(TEST_JWT_SECRET); + adminUserRepository = new InMemoryAdminUserRepository(); + SecurityPolicyRegistry policyRegistry = + new SecurityPolicyRegistry( + List.of(SecurityPolicyRoute.explicit("GET", REQUIRED_PATH, REQUIRED_AUTH))); + filter = + new AdminJwtAuthenticationFilter( + new AdminJwtAuthenticationManager( + TEST_JWT_SECRET, new CustomAdminUserDetailsService(adminUserRepository)), + policyRegistry, + request -> MaliciousPathPattern.matchesUnder(request, "/admin/api")); + admin = + adminUserRepository.save( + AdminUser.builder() + .email("admin@bottlenote.com") + .password("encoded") + .name("Admin") + .roles(List.of(AdminRole.ROOT_ADMIN)) + .status(UserStatus.ACTIVE) + .build()); + } + + @AfterEach + void tearDown() { + SecurityContextHolder.clearContext(); + } + + @Test + @DisplayName("admin access 토큰으로 요청할 때 인증 컨텍스트를 설정한다") + void accessToken_authenticates() throws Exception { + // given + String accessToken = + tokenProvider.createAdminAccessToken(admin.getEmail(), admin.getRoles(), admin.getId()); + + // when + MockHttpServletRequest request = filter(accessToken); + + // then + assertThat(request.getAttribute("exception")).isNull(); + assertThat(SecurityContextHolder.getContext().getAuthentication()).isNotNull(); + } + + @Test + @DisplayName("admin refresh 토큰을 Bearer로 요청할 때 유효하지 않은 토큰으로 처리하고 인증하지 않는다") + void refreshToken_isRejected() throws Exception { + // given + String refreshToken = + tokenProvider.createAdminRefreshToken(admin.getEmail(), admin.getRoles(), admin.getId()); + + // when + MockHttpServletRequest request = filter(refreshToken); + + // then + assertThat(request.getAttribute("exception")).isInstanceOf(MalformedJwtException.class); + assertThat(SecurityContextHolder.getContext().getAuthentication()).isNull(); + } + + @Test + @DisplayName("tokenType claim이 없는 배포 전 admin 토큰으로 요청할 때 기존처럼 인증한다") + void legacyToken_authenticates() throws Exception { + // given + Date now = new Date(); + String legacyToken = + Jwts.builder() + .setSubject(admin.getEmail()) + .claim(JwtTokenProvider.KEY_ROLES, AdminRole.ROOT_ADMIN.name()) + .claim("userId", admin.getId()) + .claim("isAdmin", true) + .setIssuedAt(now) + .setExpiration(new Date(now.getTime() + 60_000)) + .signWith( + Keys.hmacShaKeyFor(Decoders.BASE64.decode(TEST_JWT_SECRET)), + SignatureAlgorithm.HS512) + .compact(); + + // when + MockHttpServletRequest request = filter(legacyToken); + + // then + assertThat(request.getAttribute("exception")).isNull(); + assertThat(SecurityContextHolder.getContext().getAuthentication()).isNotNull(); + } + + private MockHttpServletRequest filter(String token) throws Exception { + MockHttpServletRequest request = new MockHttpServletRequest("GET", REQUIRED_PATH); + request.addHeader("Authorization", "Bearer " + token); + filter.doFilter(request, new MockHttpServletResponse(), new MockFilterChain()); + return request; + } +} diff --git a/module-domains/user/src/test/java/app/bottlenote/global/security/jwt/JwtTokenValidatorTest.java b/module-domains/user/src/test/java/app/bottlenote/global/security/jwt/JwtTokenValidatorTest.java new file mode 100644 index 000000000..0d8e7c0bc --- /dev/null +++ b/module-domains/user/src/test/java/app/bottlenote/global/security/jwt/JwtTokenValidatorTest.java @@ -0,0 +1,129 @@ +package app.bottlenote.global.security.jwt; + +import static org.assertj.core.api.Assertions.assertThat; + +import app.bottlenote.global.security.constant.JwtTokenType; +import app.bottlenote.user.constant.AdminRole; +import app.bottlenote.user.constant.UserType; +import app.bottlenote.user.dto.response.TokenItem; +import io.jsonwebtoken.Claims; +import io.jsonwebtoken.Jwts; +import io.jsonwebtoken.SignatureAlgorithm; +import io.jsonwebtoken.io.Decoders; +import io.jsonwebtoken.security.Keys; +import java.util.Date; +import java.util.List; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; + +@Tag("unit") +@DisplayName("[unit] JWT 토큰 종류 검증") +class JwtTokenValidatorTest { + + private static final String TEST_JWT_SECRET = + "dGVzdC1zZWNyZXQta2V5LWZvci1qd3QtdG9rZW4tZ2VuZXJhdGlvbi10ZXN0aW5nLXB1cnBvc2UtbG9uZy1lbm91Z2gtZm9yLWhtYWMtc2hhLTUxMi12ZXJzaW9uLWFuZC1pbXBvcnRhbnQtc2VjdXJpdHktaW4tbW9kZXJuLWphdmEtYXBwbGljYXRpb25z"; + + private final JwtTokenProvider tokenProvider = new JwtTokenProvider(TEST_JWT_SECRET); + + @BeforeEach + void setUp() { + new JwtTokenValidator(TEST_JWT_SECRET); + } + + @Test + @DisplayName("사용자 토큰을 발급할 때 access와 refresh에 각각 tokenType claim을 넣는다") + void generateToken_putsTokenTypeClaim() { + // when + TokenItem token = tokenProvider.generateToken("user@bottlenote.com", UserType.ROLE_USER, 1L); + + // then + assertThat(tokenTypeOf(token.accessToken())).isEqualTo("access"); + assertThat(tokenTypeOf(token.refreshToken())).isEqualTo("refresh"); + } + + @Test + @DisplayName("admin 토큰을 발급할 때 access와 refresh에 각각 tokenType claim을 넣는다") + void generateAdminToken_putsTokenTypeClaim() { + // when + TokenItem token = + tokenProvider.generateAdminToken( + "admin@bottlenote.com", List.of(AdminRole.ROOT_ADMIN), 1L); + + // then + assertThat(tokenTypeOf(token.accessToken())).isEqualTo("access"); + assertThat(tokenTypeOf(token.refreshToken())).isEqualTo("refresh"); + } + + @Test + @DisplayName("access 토큰을 검사할 때 Bearer 인증에는 통과하고 재발급에는 거부한다") + void accessToken_isAccessOnly() { + // given + String accessToken = + tokenProvider.createAccessToken("user@bottlenote.com", UserType.ROLE_USER, 1L); + + // when & then + assertThat(JwtTokenValidator.validateAccessToken(accessToken)).isTrue(); + assertThat(JwtTokenValidator.validateRefreshToken(accessToken)).isFalse(); + } + + @Test + @DisplayName("refresh 토큰을 검사할 때 Bearer 인증에는 거부하고 재발급에는 통과한다") + void refreshToken_isRefreshOnly() { + // given + String refreshToken = + tokenProvider.createRefreshToken("user@bottlenote.com", UserType.ROLE_USER, 1L); + + // when & then + assertThat(JwtTokenValidator.validateAccessToken(refreshToken)).isFalse(); + assertThat(JwtTokenValidator.validateRefreshToken(refreshToken)).isTrue(); + } + + @Test + @DisplayName("admin refresh 토큰을 검사할 때 Bearer 인증에는 거부한다") + void adminRefreshToken_isRejectedForAccess() { + // given + String refreshToken = + tokenProvider.createAdminRefreshToken( + "admin@bottlenote.com", List.of(AdminRole.ROOT_ADMIN), 1L); + + // when & then + assertThat(JwtTokenValidator.validateAccessToken(refreshToken)).isFalse(); + assertThat(JwtTokenValidator.validateRefreshToken(refreshToken)).isTrue(); + } + + @Test + @DisplayName("tokenType claim이 없는 배포 전 토큰을 검사할 때 Bearer 인증과 재발급 모두 통과한다") + void legacyToken_isAcceptedForBoth() { + // given + String legacyToken = legacyToken("user@bottlenote.com"); + + // when & then + assertThat(JwtTokenValidator.validateAccessToken(legacyToken)).isTrue(); + assertThat(JwtTokenValidator.validateRefreshToken(legacyToken)).isTrue(); + } + + private static String tokenTypeOf(String token) { + Claims claims = + Jwts.parserBuilder() + .setSigningKey(Keys.hmacShaKeyFor(Decoders.BASE64.decode(TEST_JWT_SECRET))) + .build() + .parseClaimsJws(token) + .getBody(); + return claims.get(JwtTokenType.CLAIM_NAME, String.class); + } + + private static String legacyToken(String email) { + Date now = new Date(); + return Jwts.builder() + .setSubject(email) + .claim(JwtTokenProvider.KEY_ROLES, UserType.ROLE_USER.name()) + .claim("userId", 1L) + .setIssuedAt(now) + .setExpiration(new Date(now.getTime() + 60_000)) + .signWith( + Keys.hmacShaKeyFor(Decoders.BASE64.decode(TEST_JWT_SECRET)), SignatureAlgorithm.HS512) + .compact(); + } +} diff --git a/module-domains/user/src/test/java/app/bottlenote/user/service/AdminAuthServiceTest.java b/module-domains/user/src/test/java/app/bottlenote/user/service/AdminAuthServiceTest.java index f7629933e..3925aec40 100644 --- a/module-domains/user/src/test/java/app/bottlenote/user/service/AdminAuthServiceTest.java +++ b/module-domains/user/src/test/java/app/bottlenote/user/service/AdminAuthServiceTest.java @@ -13,6 +13,7 @@ import app.bottlenote.global.security.CustomAdminUserDetailsService; import app.bottlenote.global.security.jwt.AdminJwtAuthenticationManager; import app.bottlenote.global.security.jwt.JwtTokenProvider; +import app.bottlenote.global.security.jwt.JwtTokenValidator; import app.bottlenote.user.constant.AdminRole; import app.bottlenote.user.constant.UserStatus; import app.bottlenote.user.domain.AdminUser; @@ -20,6 +21,11 @@ import app.bottlenote.user.exception.UserException; import app.bottlenote.user.exception.UserExceptionCode; import app.bottlenote.user.fixture.InMemoryAdminUserRepository; +import io.jsonwebtoken.Jwts; +import io.jsonwebtoken.SignatureAlgorithm; +import io.jsonwebtoken.io.Decoders; +import io.jsonwebtoken.security.Keys; +import java.util.Date; import java.util.List; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.DisplayName; @@ -43,8 +49,12 @@ private static String apiKey(char value) { AgentFacade agentFacade; AdminAuthService adminAuthService; + JwtTokenProvider tokenProvider; + @BeforeEach void setUp() { + new JwtTokenValidator(TEST_JWT_SECRET); + tokenProvider = new JwtTokenProvider(TEST_JWT_SECRET); adminUserRepository = new InMemoryAdminUserRepository(); agentRepository = new InMemoryAgentRepository(); agentFacade = new DefaultAgentFacade(agentRepository); @@ -52,7 +62,7 @@ void setUp() { adminAuthService = new AdminAuthService( adminUserRepository, - new JwtTokenProvider(TEST_JWT_SECRET), + tokenProvider, new AdminJwtAuthenticationManager( TEST_JWT_SECRET, new CustomAdminUserDetailsService(adminUserRepository)), new BCryptPasswordEncoder(), @@ -205,4 +215,70 @@ void loginWithAgent_inactiveAdmin_throwsAuthenticationFailed() { assertThat(exception.getExceptionCode()) .isEqualTo(UserExceptionCode.AGENT_AUTHENTICATION_FAILED); } + + @Test + @DisplayName("refresh 토큰으로 재발급을 요청할 때 새 토큰을 발급한다") + void refresh_withRefreshToken_reissues() { + // given + AdminUser admin = saveActiveAdmin(); + String refreshToken = + tokenProvider.createAdminRefreshToken(admin.getEmail(), admin.getRoles(), admin.getId()); + admin.updateRefreshToken(refreshToken); + + // when + TokenItem token = adminAuthService.refresh(refreshToken); + + // then + assertThat(token.accessToken()).isNotBlank(); + assertThat(token.refreshToken()).isNotBlank(); + assertThat(admin.getRefreshToken()).isEqualTo(token.refreshToken()); + } + + @Test + @DisplayName("tokenType claim이 없는 배포 전 refresh 토큰으로 재발급을 요청할 때 새 토큰을 발급한다") + void refresh_withLegacyRefreshToken_reissues() { + // given + AdminUser admin = saveActiveAdmin(); + String legacyRefreshToken = legacyAdminToken(admin); + admin.updateRefreshToken(legacyRefreshToken); + + // when + TokenItem token = adminAuthService.refresh(legacyRefreshToken); + + // then + assertThat(token.accessToken()).isNotBlank(); + assertThat(token.refreshToken()).isNotBlank(); + } + + @Test + @DisplayName("access 종류로 명시된 토큰으로 재발급을 요청할 때 INVALID_REFRESH_TOKEN 예외가 발생한다") + void refresh_withAccessToken_throwsInvalidRefreshToken() { + // given + AdminUser admin = saveActiveAdmin(); + String accessToken = + tokenProvider.createAdminAccessToken(admin.getEmail(), admin.getRoles(), admin.getId()); + // 저장소 조회가 통과하더라도 토큰 종류 검사로 거부되는지 확인한다 + admin.updateRefreshToken(accessToken); + + // when + UserException exception = + assertThrows(UserException.class, () -> adminAuthService.refresh(accessToken)); + + // then + assertThat(exception.getExceptionCode()).isEqualTo(UserExceptionCode.INVALID_REFRESH_TOKEN); + } + + private static String legacyAdminToken(AdminUser admin) { + Date now = new Date(); + return Jwts.builder() + .setSubject(admin.getEmail()) + .claim(JwtTokenProvider.KEY_ROLES, AdminRole.ROOT_ADMIN.name()) + .claim("userId", admin.getId()) + .claim("isAdmin", true) + .setIssuedAt(now) + .setExpiration(new Date(now.getTime() + 60_000)) + .signWith( + Keys.hmacShaKeyFor(Decoders.BASE64.decode(TEST_JWT_SECRET)), SignatureAlgorithm.HS512) + .compact(); + } } From e18f0c7226d7a5344c0254eed707a220e34b3aaf Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 30 Nov 2026 17:15:30 +0900 Subject: [PATCH 2/3] =?UTF-8?q?fix:=20=ED=83=88=ED=87=B4=ED=95=9C=20?= =?UTF-8?q?=EC=82=AC=EC=9A=A9=EC=9E=90=EC=9D=98=20=ED=86=A0=ED=81=B0?= =?UTF-8?q?=EC=9C=BC=EB=A1=9C=20=EC=9D=B8=EC=A6=9D=ED=95=A0=20=EC=88=98=20?= =?UTF-8?q?=EC=97=86=EA=B2=8C=20=ED=95=9C=EB=8B=A4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 탈퇴는 users.status만 DELETED로 바꾸고 email과 행을 유지하므로 CustomUserDetailsService가 findByEmail만으로 탈퇴 사용자를 인증하고 있었다. 살아 있지 않은 사용자는 UsernameNotFoundException으로 거부한다. JwtAuthenticationFilter가 UsernameNotFoundException을 잡지 않아 존재하지 않는 사용자의 토큰이 필터 밖으로 예외를 던져 500이 되던 문제도 요청 attribute exception 설정 후 401로 처리하도록 함께 바로잡는다. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01DNr3PM1DZCQLC8RiGJwD3a --- .../jwt/JwtAuthenticationFilterTest.java | 32 +++++++++++++++++++ .../UserCommandIntegrationTest.java | 29 +++++++++++++++-- .../AdminApiSecurityIntegrationTest.java | 20 +++++------- .../security/CustomUserDetailsService.java | 5 +++ .../security/jwt/JwtAuthenticationFilter.java | 4 +++ 5 files changed, 76 insertions(+), 14 deletions(-) diff --git a/bottlenote-api/src/test/java/app/bottlenote/global/security/jwt/JwtAuthenticationFilterTest.java b/bottlenote-api/src/test/java/app/bottlenote/global/security/jwt/JwtAuthenticationFilterTest.java index ad9897165..27b3121f1 100644 --- a/bottlenote-api/src/test/java/app/bottlenote/global/security/jwt/JwtAuthenticationFilterTest.java +++ b/bottlenote-api/src/test/java/app/bottlenote/global/security/jwt/JwtAuthenticationFilterTest.java @@ -27,6 +27,7 @@ import org.springframework.mock.web.MockHttpServletRequest; import org.springframework.mock.web.MockHttpServletResponse; import org.springframework.security.core.context.SecurityContextHolder; +import org.springframework.security.core.userdetails.UsernameNotFoundException; @Tag("unit") @DisplayName("[unit] product JWT 필터의 토큰 판정") @@ -105,6 +106,37 @@ void legacyToken_authenticates() throws Exception { assertThat(SecurityContextHolder.getContext().getAuthentication()).isNotNull(); } + @Test + @DisplayName("탈퇴한 사용자의 access 토큰으로 요청할 때 인증 실패로 처리하고 예외를 밖으로 던지지 않는다") + void withdrawnUserToken_isRejected() throws Exception { + // given + String accessToken = + tokenProvider.createAccessToken(user.getEmail(), user.getRole(), user.getId()); + user.withdrawUser(); + + // when + MockHttpServletRequest request = filter(accessToken); + + // then + assertThat(request.getAttribute("exception")).isInstanceOf(UsernameNotFoundException.class); + assertThat(SecurityContextHolder.getContext().getAuthentication()).isNull(); + } + + @Test + @DisplayName("존재하지 않는 사용자의 토큰으로 요청할 때 인증 실패로 처리하고 예외를 밖으로 던지지 않는다") + void unknownUserToken_isRejected() throws Exception { + // given + String accessToken = + tokenProvider.createAccessToken("unknown@bottlenote.com", UserType.ROLE_USER, 999L); + + // when + MockHttpServletRequest request = filter(accessToken); + + // then + assertThat(request.getAttribute("exception")).isInstanceOf(UsernameNotFoundException.class); + assertThat(SecurityContextHolder.getContext().getAuthentication()).isNull(); + } + private MockHttpServletRequest filter(String token) throws Exception { MockHttpServletRequest request = new MockHttpServletRequest("PUT", REQUIRED_PATH); request.addHeader("Authorization", "Bearer " + token); diff --git a/bottlenote-api/src/test/java/app/bottlenote/user/integration/UserCommandIntegrationTest.java b/bottlenote-api/src/test/java/app/bottlenote/user/integration/UserCommandIntegrationTest.java index 07c49650a..138649e97 100644 --- a/bottlenote-api/src/test/java/app/bottlenote/user/integration/UserCommandIntegrationTest.java +++ b/bottlenote-api/src/test/java/app/bottlenote/user/integration/UserCommandIntegrationTest.java @@ -24,6 +24,7 @@ import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; +import org.springframework.security.test.context.support.WithAnonymousUser; import org.springframework.security.test.context.support.WithMockUser; import org.springframework.test.web.servlet.assertj.MvcTestResult; @@ -61,8 +62,10 @@ void test_1() throws Exception { .ifPresent(withdraw -> assertEquals(DELETED, withdraw.getStatus())); } - @DisplayName("탈퇴한 회원이 다시 탈퇴하는 경우 성공") + @DisplayName("탈퇴한 회원의 토큰으로 다시 탈퇴를 요청할 때 401을 반환한다") @Test + // 클래스의 @WithMockUser 인증이 남으면 토큰 거부가 가려지므로 익명 컨텍스트로 시작한다 + @WithAnonymousUser void test_2() throws Exception { // Given User user = userTestFactory.persistUser(); @@ -84,7 +87,29 @@ void test_2() throws Exception { .exchange(); // Then - result.assertThat().hasStatusOk(); + result.assertThat().hasStatus(HttpStatus.UNAUTHORIZED); + } + + @DisplayName("탈퇴한 회원의 토큰으로 인증 필수 API를 호출할 때 401을 반환한다") + @Test + @WithAnonymousUser + void withdrawnUserToken_isUnauthorized() throws Exception { + // Given + User user = userTestFactory.persistUser(); + TokenItem token = getToken(user); + user.withdrawUser(); + userRepository.save(user); + + // When + MvcTestResult result = + mockMvcTester + .get() + .uri("/api/v1/users/current") + .header("Authorization", "Bearer " + token.accessToken()) + .exchange(); + + // Then + result.assertThat().hasStatus(HttpStatus.UNAUTHORIZED); } @DisplayName("닉네임 변경에 성공한다.") diff --git a/bottlenote-api/src/test/java/app/global/admin/AdminApiSecurityIntegrationTest.java b/bottlenote-api/src/test/java/app/global/admin/AdminApiSecurityIntegrationTest.java index dbdfafc1d..f88d2fadd 100644 --- a/bottlenote-api/src/test/java/app/global/admin/AdminApiSecurityIntegrationTest.java +++ b/bottlenote-api/src/test/java/app/global/admin/AdminApiSecurityIntegrationTest.java @@ -1,7 +1,6 @@ package app.global.admin; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.catchThrowable; import app.bottlenote.global.annotation.SecurityPolicy.AuthType; import app.bottlenote.global.security.jwt.JwtTokenProvider; @@ -23,12 +22,10 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.beans.factory.annotation.Value; -import org.springframework.core.NestedExceptionUtils; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpMethod; import org.springframework.http.MediaType; import org.springframework.mock.web.MockHttpServletResponse; -import org.springframework.security.core.userdetails.UsernameNotFoundException; import org.springframework.test.web.servlet.MvcResult; import org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder; import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; @@ -143,15 +140,14 @@ class AdminApiSecurityIntegrationTest extends AdminApiIntegrationTestSupport { .accessToken(); // product의 JwtAuthenticationManager는 isAdmin을 보지 않고 users에서 이메일로 사용자를 찾는다. - // admin 이메일이 users에 없으면 필터에서 예외가 나는 기존 동작을 유지한다(실서버에서는 500). - Throwable thrown = - catchThrowable( - () -> - mockMvc.perform( - MockMvcRequestBuilders.get("/api/v1/my-page/1/my-bottle/reviews") - .header(HttpHeaders.AUTHORIZATION, "Bearer " + adminToken))); - assertThat(NestedExceptionUtils.getMostSpecificCause(thrown)) - .isInstanceOf(UsernameNotFoundException.class); + // admin 이메일이 users에 없으면 필터가 인증 실패로 처리해 401을 반환한다. + MvcResult protectedResult = + mockMvc + .perform( + MockMvcRequestBuilders.get("/api/v1/my-page/1/my-bottle/reviews") + .header(HttpHeaders.AUTHORIZATION, "Bearer " + adminToken)) + .andReturn(); + assertThat(protectedResult.getResponse().getStatus()).isEqualTo(401); // 공개 API는 토큰과 무관하게 기존처럼 응답한다 MvcResult publicResult = diff --git a/module-domains/user/src/main/java/app/bottlenote/global/security/CustomUserDetailsService.java b/module-domains/user/src/main/java/app/bottlenote/global/security/CustomUserDetailsService.java index ea4e93eec..0604f91bb 100644 --- a/module-domains/user/src/main/java/app/bottlenote/global/security/CustomUserDetailsService.java +++ b/module-domains/user/src/main/java/app/bottlenote/global/security/CustomUserDetailsService.java @@ -29,6 +29,11 @@ public UserDetails loadUserByUsername(String email) throws UsernameNotFoundExcep .findByEmail(email) .orElseThrow(() -> new UsernameNotFoundException("사용자를 찾을 수 없습니다.")); + // 탈퇴는 status만 바꾸고 email을 유지하므로 탈퇴 사용자의 토큰도 여기서 막는다 + if (!customUser.isAlive()) { + throw new UsernameNotFoundException("탈퇴한 사용자입니다."); + } + List authorities = new ArrayList<>(); authorities.add(new SimpleGrantedAuthority(customUser.getRole().toString())); diff --git a/module-domains/user/src/main/java/app/bottlenote/global/security/jwt/JwtAuthenticationFilter.java b/module-domains/user/src/main/java/app/bottlenote/global/security/jwt/JwtAuthenticationFilter.java index 93ee7b80b..ced740536 100644 --- a/module-domains/user/src/main/java/app/bottlenote/global/security/jwt/JwtAuthenticationFilter.java +++ b/module-domains/user/src/main/java/app/bottlenote/global/security/jwt/JwtAuthenticationFilter.java @@ -18,6 +18,7 @@ import org.springframework.lang.NonNull; import org.springframework.security.core.Authentication; import org.springframework.security.core.context.SecurityContextHolder; +import org.springframework.security.core.userdetails.UsernameNotFoundException; import org.springframework.web.cors.CorsUtils; import org.springframework.web.filter.OncePerRequestFilter; @@ -87,6 +88,9 @@ protected void doFilterInternal( } catch (CustomJwtException e) { log.warn("JWT 토큰이 존재하지 않습니다. {} ", e.getMessage()); request.setAttribute("exception", e); + } catch (UsernameNotFoundException e) { + log.warn("토큰의 사용자를 인증할 수 없습니다. {} ", e.getMessage()); + request.setAttribute("exception", e); } filterChain.doFilter(request, response); } From a3722c1125da6e9b93408b15feb8036690921e07 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 30 Nov 2026 17:23:20 +0900 Subject: [PATCH 3/3] =?UTF-8?q?test:=20admin=20=ED=86=A0=ED=81=B0=EC=9D=98?= =?UTF-8?q?=20product=20API=20=ED=98=B8=EC=B6=9C=20=EA=B8=B0=EB=8C=80?= =?UTF-8?q?=EA=B0=92=EC=9D=84=20401=EB=A1=9C=20=EB=A7=9E=EC=B6=98=EB=8B=A4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 존재하지 않는 사용자의 토큰이 500 대신 401로 응답하게 된 변경을 HTTP 경계 테스트에 반영한다. Co-Authored-By: Claude Mythos 5.2 Claude-Session: https://claude.ai/code/session_01DNr3PM1DZCQLC8RiGJwD3a --- .../global/admin/AdminApiHttpBoundaryIntegrationTest.java | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/bottlenote-api/src/test/java/app/global/admin/AdminApiHttpBoundaryIntegrationTest.java b/bottlenote-api/src/test/java/app/global/admin/AdminApiHttpBoundaryIntegrationTest.java index 46608339f..55ab5db7a 100644 --- a/bottlenote-api/src/test/java/app/global/admin/AdminApiHttpBoundaryIntegrationTest.java +++ b/bottlenote-api/src/test/java/app/global/admin/AdminApiHttpBoundaryIntegrationTest.java @@ -147,12 +147,12 @@ class AdminApiHttpBoundaryIntegrationTest extends AdminApiIntegrationTestSupport } @Test - @DisplayName("admin 토큰으로 product API를 호출할 때 기존 product 동작(인증 필수는 500, 공개는 200)을 유지한다") - void admin_토큰_product_요청은_기존_동작() throws Exception { + @DisplayName("admin 토큰으로 product API를 호출할 때 인증 필수는 401, 공개는 200으로 응답한다") + void admin_토큰_product_요청은_인증_필수만_거부한다() throws Exception { String token = adminToken(); - // admin 이메일이 users에 없으면 product JWT 필터에서 예외가 나 서버 오류로 끝나는 기존 동작이다 - assertThat(get("/api/v1/business-support", token).statusCode()).isEqualTo(500); + // admin 이메일이 users에 없으면 product JWT 필터가 인증 실패로 처리한다 + assertThat(get("/api/v1/business-support", token).statusCode()).isEqualTo(401); assertThat(get("/api/v1/alcohols/categories", token).statusCode()).isEqualTo(200); }