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..27b3121f1 --- /dev/null +++ b/bottlenote-api/src/test/java/app/bottlenote/global/security/jwt/JwtAuthenticationFilterTest.java @@ -0,0 +1,168 @@ +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; +import org.springframework.security.core.userdetails.UsernameNotFoundException; + +@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(); + } + + @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); + 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/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/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/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); } 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..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; @@ -98,6 +95,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 { @@ -124,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/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..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; @@ -58,7 +59,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); @@ -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); } 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(); + } }