From e2b1fee0b39be6c68e4b277eec7cc4f2e0a3331b Mon Sep 17 00:00:00 2001 From: DongilMin Date: Fri, 27 Sep 2024 07:26:19 +0900 Subject: [PATCH 1/9] [Refactor/InhaBas#168] CookieUtilsTest Code Refactoring --- .../domain/oauth2/cookie/CookieUtilsTest.java | 139 +++++++----------- 1 file changed, 57 insertions(+), 82 deletions(-) diff --git a/module-auth/src/test/java/com/inhabas/api/auth/domain/oauth2/cookie/CookieUtilsTest.java b/module-auth/src/test/java/com/inhabas/api/auth/domain/oauth2/cookie/CookieUtilsTest.java index 31af7b3b..38e8a88d 100644 --- a/module-auth/src/test/java/com/inhabas/api/auth/domain/oauth2/cookie/CookieUtilsTest.java +++ b/module-auth/src/test/java/com/inhabas/api/auth/domain/oauth2/cookie/CookieUtilsTest.java @@ -1,43 +1,40 @@ package com.inhabas.api.auth.domain.oauth2.cookie; - import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.jupiter.api.Assertions.assertTrue; - import java.lang.reflect.Constructor; -import java.lang.reflect.InvocationTargetException; import java.util.Optional; import java.util.Set; import javax.servlet.http.Cookie; +import org.apache.commons.codec.binary.Base64; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; import org.springframework.mock.web.MockHttpServletRequest; import org.springframework.mock.web.MockHttpServletResponse; import org.springframework.security.oauth2.core.AuthorizationGrantType; import org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationRequest; -import org.apache.commons.codec.binary.Base64; - -import org.junit.jupiter.api.DisplayName; -import org.junit.jupiter.api.Test; - public class CookieUtilsTest { + private static final String COOKIE_NAME = "myCookie"; + private static final String COOKIE_CONTENTS = "hello"; + private static final int COOKIE_MAX_AGE = 180; + @DisplayName("request 에서 쿠키를 꺼낸다.") @Test public void resolveCookieFromRequest() { // given - MockHttpServletRequest request = new MockHttpServletRequest(); - Cookie cookie = new Cookie("myCookie", "hello"); - cookie.setMaxAge(180); - request.setCookies(cookie); + MockHttpServletRequest request = createRequestWithCookie(COOKIE_NAME, COOKIE_CONTENTS, COOKIE_MAX_AGE); // when - Optional myCookie = CookieUtils.resolveCookie(request, "myCookie"); + Optional myCookie = CookieUtils.resolveCookie(request, COOKIE_NAME); // then - assertThat(myCookie.isPresent()).isTrue(); - assertThat(myCookie.get().getValue()).isEqualTo("hello"); - assertThat(myCookie.get().getMaxAge()).isEqualTo(180); + assertThat(myCookie).isPresent() + .hasValueSatisfying(cookie -> { + assertThat(cookie.getValue()).isEqualTo(COOKIE_CONTENTS); + assertThat(cookie.getMaxAge()).isEqualTo(COOKIE_MAX_AGE); + }); } @DisplayName("response 에 쿠키를 저장한다.") @@ -45,19 +42,18 @@ public void resolveCookieFromRequest() { public void saveCookieToResponse() { // given MockHttpServletResponse response = new MockHttpServletResponse(); - String cookieName = "myCookie"; - String cookieContents = "hello"; // when - CookieUtils.setCookie(response, cookieName, cookieContents, 180); + CookieUtils.setCookie(response, COOKIE_NAME, COOKIE_CONTENTS, COOKIE_MAX_AGE); // then - Cookie resolvedCookie = response.getCookie(cookieName); - assert resolvedCookie != null; - - assertThat(resolvedCookie.getName()).isEqualTo(cookieName); - assertThat(resolvedCookie.getValue()).isEqualTo(cookieContents); - assertThat(resolvedCookie.getMaxAge()).isEqualTo(180); + Cookie resolvedCookie = response.getCookie(COOKIE_NAME); + assertThat(resolvedCookie).isNotNull() + .satisfies(cookie -> { + assertThat(cookie.getName()).isEqualTo(COOKIE_NAME); + assertThat(cookie.getValue()).isEqualTo(COOKIE_CONTENTS); + assertThat(cookie.getMaxAge()).isEqualTo(COOKIE_MAX_AGE); + }); } @DisplayName("request 에서 쿠키를 지운다.") @@ -65,72 +61,61 @@ public void saveCookieToResponse() { public void removeCookieOfRequest() { // given MockHttpServletResponse response = new MockHttpServletResponse(); - MockHttpServletRequest request = new MockHttpServletRequest(); - Cookie cookie = new Cookie("myCookie", "hello"); - cookie.setMaxAge(180); - request.setCookies(cookie); + MockHttpServletRequest request = createRequestWithCookie(COOKIE_NAME, COOKIE_CONTENTS, COOKIE_MAX_AGE); // when - CookieUtils.deleteCookie(request, response, "myCookie"); + CookieUtils.deleteCookie(request, response, COOKIE_NAME); // then - Cookie deletedCookie = response.getCookie("myCookie"); - assert deletedCookie != null; - assertThat(deletedCookie.getMaxAge()).isEqualTo(0); - assertThat(deletedCookie.getValue()).isEqualTo(""); + Cookie deletedCookie = response.getCookie(COOKIE_NAME); + assertThat(deletedCookie).isNotNull() + .satisfies(cookie -> { + assertThat(cookie.getMaxAge()).isEqualTo(0); + assertThat(cookie.getValue()).isEqualTo(""); + }); } @DisplayName("성공적으로 serialize 한다.") @Test - public void serializingTest() - throws InvocationTargetException, InstantiationException, IllegalAccessException, - NoSuchMethodException { - // reflection - Constructor constructor = - OAuth2AuthorizationRequest.Builder.class.getDeclaredConstructor( - AuthorizationGrantType.class); - constructor.setAccessible(true); - - // given - OAuth2AuthorizationRequest.Builder builder = - (OAuth2AuthorizationRequest.Builder) - constructor.newInstance(AuthorizationGrantType.AUTHORIZATION_CODE); - OAuth2AuthorizationRequest request = - builder - .authorizationUri("https://kauth.kakao.com/oauth/authorize") - .clientId("1234") - .redirectUri("http://localhost/api/login/oauth2/code/kakao") - .scopes(Set.of("gender", "profile_image", "account_email", "profile_nickname")) - .state("state1934") - .additionalParameters(java.util.Map.of()) - .attributes(java.util.Map.of("registration_id", "kakao")) - .build(); + public void serializingTest() throws Exception { + OAuth2AuthorizationRequest request = createOAuth2AuthorizationRequest(); // when String serializedRequest = CookieUtils.serialize(request); // then - assertTrue(Base64.isBase64(serializedRequest)); + assertThat(serializedRequest).matches(Base64::isBase64); } @DisplayName("성공적으로 deserialize 한다.") @Test - public void deserializingTest() - throws NoSuchMethodException, InvocationTargetException, InstantiationException, - IllegalAccessException { + public void deserializingTest() throws Exception { + OAuth2AuthorizationRequest originalRequest = createOAuth2AuthorizationRequest(); + String serializedRequest = CookieUtils.serialize(originalRequest); + Cookie cookie = new Cookie("base64", serializedRequest); + + // when + OAuth2AuthorizationRequest deserializedRequest = CookieUtils.deserialize(cookie, OAuth2AuthorizationRequest.class); + + // then + assertThat(deserializedRequest).usingRecursiveComparison().isEqualTo(originalRequest); + } + + private MockHttpServletRequest createRequestWithCookie(String name, String value, int maxAge) { + MockHttpServletRequest request = new MockHttpServletRequest(); + Cookie cookie = new Cookie(name, value); + cookie.setMaxAge(maxAge); + request.setCookies(cookie); + return request; + } + static private OAuth2AuthorizationRequest createOAuth2AuthorizationRequest() throws Exception { // reflection - Constructor constructor = - OAuth2AuthorizationRequest.Builder.class.getDeclaredConstructor( - AuthorizationGrantType.class); + Constructor constructor = OAuth2AuthorizationRequest.Builder.class.getDeclaredConstructor(AuthorizationGrantType.class); constructor.setAccessible(true); - // given - OAuth2AuthorizationRequest.Builder builder = - (OAuth2AuthorizationRequest.Builder) - constructor.newInstance(AuthorizationGrantType.AUTHORIZATION_CODE); - OAuth2AuthorizationRequest originalRequest = - builder + OAuth2AuthorizationRequest.Builder builder = (OAuth2AuthorizationRequest.Builder) constructor.newInstance(AuthorizationGrantType.AUTHORIZATION_CODE); + return builder .authorizationUri("https://kauth.kakao.com/oauth/authorize") .clientId("1234") .redirectUri("http://localhost/api/login/oauth2/code/kakao") @@ -139,15 +124,5 @@ public void deserializingTest() .additionalParameters(java.util.Map.of()) .attributes(java.util.Map.of("registration_id", "kakao")) .build(); - - String serializedRequest = CookieUtils.serialize(originalRequest); - Cookie cookie = new Cookie("base64", serializedRequest); - - // when - OAuth2AuthorizationRequest deserializedRequest = - CookieUtils.deserialize(cookie, OAuth2AuthorizationRequest.class); - - // then - assertThat(deserializedRequest).usingRecursiveComparison().isEqualTo(originalRequest); } -} +} \ No newline at end of file From 4392fb7e51e70d9c824fd65418052c0b848f87f0 Mon Sep 17 00:00:00 2001 From: DongilMin Date: Fri, 27 Sep 2024 07:29:35 +0900 Subject: [PATCH 2/9] return --- .../domain/oauth2/cookie/CookieUtilsTest.java | 139 +++++++++++------- 1 file changed, 82 insertions(+), 57 deletions(-) diff --git a/module-auth/src/test/java/com/inhabas/api/auth/domain/oauth2/cookie/CookieUtilsTest.java b/module-auth/src/test/java/com/inhabas/api/auth/domain/oauth2/cookie/CookieUtilsTest.java index 38e8a88d..31af7b3b 100644 --- a/module-auth/src/test/java/com/inhabas/api/auth/domain/oauth2/cookie/CookieUtilsTest.java +++ b/module-auth/src/test/java/com/inhabas/api/auth/domain/oauth2/cookie/CookieUtilsTest.java @@ -1,40 +1,43 @@ package com.inhabas.api.auth.domain.oauth2.cookie; + import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.jupiter.api.Assertions.assertTrue; + import java.lang.reflect.Constructor; +import java.lang.reflect.InvocationTargetException; import java.util.Optional; import java.util.Set; import javax.servlet.http.Cookie; -import org.apache.commons.codec.binary.Base64; -import org.junit.jupiter.api.DisplayName; -import org.junit.jupiter.api.Test; import org.springframework.mock.web.MockHttpServletRequest; import org.springframework.mock.web.MockHttpServletResponse; import org.springframework.security.oauth2.core.AuthorizationGrantType; import org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationRequest; -public class CookieUtilsTest { +import org.apache.commons.codec.binary.Base64; - private static final String COOKIE_NAME = "myCookie"; - private static final String COOKIE_CONTENTS = "hello"; - private static final int COOKIE_MAX_AGE = 180; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +public class CookieUtilsTest { @DisplayName("request 에서 쿠키를 꺼낸다.") @Test public void resolveCookieFromRequest() { // given - MockHttpServletRequest request = createRequestWithCookie(COOKIE_NAME, COOKIE_CONTENTS, COOKIE_MAX_AGE); + MockHttpServletRequest request = new MockHttpServletRequest(); + Cookie cookie = new Cookie("myCookie", "hello"); + cookie.setMaxAge(180); + request.setCookies(cookie); // when - Optional myCookie = CookieUtils.resolveCookie(request, COOKIE_NAME); + Optional myCookie = CookieUtils.resolveCookie(request, "myCookie"); // then - assertThat(myCookie).isPresent() - .hasValueSatisfying(cookie -> { - assertThat(cookie.getValue()).isEqualTo(COOKIE_CONTENTS); - assertThat(cookie.getMaxAge()).isEqualTo(COOKIE_MAX_AGE); - }); + assertThat(myCookie.isPresent()).isTrue(); + assertThat(myCookie.get().getValue()).isEqualTo("hello"); + assertThat(myCookie.get().getMaxAge()).isEqualTo(180); } @DisplayName("response 에 쿠키를 저장한다.") @@ -42,18 +45,19 @@ public void resolveCookieFromRequest() { public void saveCookieToResponse() { // given MockHttpServletResponse response = new MockHttpServletResponse(); + String cookieName = "myCookie"; + String cookieContents = "hello"; // when - CookieUtils.setCookie(response, COOKIE_NAME, COOKIE_CONTENTS, COOKIE_MAX_AGE); + CookieUtils.setCookie(response, cookieName, cookieContents, 180); // then - Cookie resolvedCookie = response.getCookie(COOKIE_NAME); - assertThat(resolvedCookie).isNotNull() - .satisfies(cookie -> { - assertThat(cookie.getName()).isEqualTo(COOKIE_NAME); - assertThat(cookie.getValue()).isEqualTo(COOKIE_CONTENTS); - assertThat(cookie.getMaxAge()).isEqualTo(COOKIE_MAX_AGE); - }); + Cookie resolvedCookie = response.getCookie(cookieName); + assert resolvedCookie != null; + + assertThat(resolvedCookie.getName()).isEqualTo(cookieName); + assertThat(resolvedCookie.getValue()).isEqualTo(cookieContents); + assertThat(resolvedCookie.getMaxAge()).isEqualTo(180); } @DisplayName("request 에서 쿠키를 지운다.") @@ -61,61 +65,72 @@ public void saveCookieToResponse() { public void removeCookieOfRequest() { // given MockHttpServletResponse response = new MockHttpServletResponse(); - MockHttpServletRequest request = createRequestWithCookie(COOKIE_NAME, COOKIE_CONTENTS, COOKIE_MAX_AGE); + MockHttpServletRequest request = new MockHttpServletRequest(); + Cookie cookie = new Cookie("myCookie", "hello"); + cookie.setMaxAge(180); + request.setCookies(cookie); // when - CookieUtils.deleteCookie(request, response, COOKIE_NAME); + CookieUtils.deleteCookie(request, response, "myCookie"); // then - Cookie deletedCookie = response.getCookie(COOKIE_NAME); - assertThat(deletedCookie).isNotNull() - .satisfies(cookie -> { - assertThat(cookie.getMaxAge()).isEqualTo(0); - assertThat(cookie.getValue()).isEqualTo(""); - }); + Cookie deletedCookie = response.getCookie("myCookie"); + assert deletedCookie != null; + assertThat(deletedCookie.getMaxAge()).isEqualTo(0); + assertThat(deletedCookie.getValue()).isEqualTo(""); } @DisplayName("성공적으로 serialize 한다.") @Test - public void serializingTest() throws Exception { - OAuth2AuthorizationRequest request = createOAuth2AuthorizationRequest(); + public void serializingTest() + throws InvocationTargetException, InstantiationException, IllegalAccessException, + NoSuchMethodException { + // reflection + Constructor constructor = + OAuth2AuthorizationRequest.Builder.class.getDeclaredConstructor( + AuthorizationGrantType.class); + constructor.setAccessible(true); + + // given + OAuth2AuthorizationRequest.Builder builder = + (OAuth2AuthorizationRequest.Builder) + constructor.newInstance(AuthorizationGrantType.AUTHORIZATION_CODE); + OAuth2AuthorizationRequest request = + builder + .authorizationUri("https://kauth.kakao.com/oauth/authorize") + .clientId("1234") + .redirectUri("http://localhost/api/login/oauth2/code/kakao") + .scopes(Set.of("gender", "profile_image", "account_email", "profile_nickname")) + .state("state1934") + .additionalParameters(java.util.Map.of()) + .attributes(java.util.Map.of("registration_id", "kakao")) + .build(); // when String serializedRequest = CookieUtils.serialize(request); // then - assertThat(serializedRequest).matches(Base64::isBase64); + assertTrue(Base64.isBase64(serializedRequest)); } @DisplayName("성공적으로 deserialize 한다.") @Test - public void deserializingTest() throws Exception { - OAuth2AuthorizationRequest originalRequest = createOAuth2AuthorizationRequest(); - String serializedRequest = CookieUtils.serialize(originalRequest); - Cookie cookie = new Cookie("base64", serializedRequest); - - // when - OAuth2AuthorizationRequest deserializedRequest = CookieUtils.deserialize(cookie, OAuth2AuthorizationRequest.class); - - // then - assertThat(deserializedRequest).usingRecursiveComparison().isEqualTo(originalRequest); - } - - private MockHttpServletRequest createRequestWithCookie(String name, String value, int maxAge) { - MockHttpServletRequest request = new MockHttpServletRequest(); - Cookie cookie = new Cookie(name, value); - cookie.setMaxAge(maxAge); - request.setCookies(cookie); - return request; - } + public void deserializingTest() + throws NoSuchMethodException, InvocationTargetException, InstantiationException, + IllegalAccessException { - static private OAuth2AuthorizationRequest createOAuth2AuthorizationRequest() throws Exception { // reflection - Constructor constructor = OAuth2AuthorizationRequest.Builder.class.getDeclaredConstructor(AuthorizationGrantType.class); + Constructor constructor = + OAuth2AuthorizationRequest.Builder.class.getDeclaredConstructor( + AuthorizationGrantType.class); constructor.setAccessible(true); - OAuth2AuthorizationRequest.Builder builder = (OAuth2AuthorizationRequest.Builder) constructor.newInstance(AuthorizationGrantType.AUTHORIZATION_CODE); - return builder + // given + OAuth2AuthorizationRequest.Builder builder = + (OAuth2AuthorizationRequest.Builder) + constructor.newInstance(AuthorizationGrantType.AUTHORIZATION_CODE); + OAuth2AuthorizationRequest originalRequest = + builder .authorizationUri("https://kauth.kakao.com/oauth/authorize") .clientId("1234") .redirectUri("http://localhost/api/login/oauth2/code/kakao") @@ -124,5 +139,15 @@ static private OAuth2AuthorizationRequest createOAuth2AuthorizationRequest() thr .additionalParameters(java.util.Map.of()) .attributes(java.util.Map.of("registration_id", "kakao")) .build(); + + String serializedRequest = CookieUtils.serialize(originalRequest); + Cookie cookie = new Cookie("base64", serializedRequest); + + // when + OAuth2AuthorizationRequest deserializedRequest = + CookieUtils.deserialize(cookie, OAuth2AuthorizationRequest.class); + + // then + assertThat(deserializedRequest).usingRecursiveComparison().isEqualTo(originalRequest); } -} \ No newline at end of file +} From 6b1e54d13706f48ba0c3aa0e694dfcaeb61df22f Mon Sep 17 00:00:00 2001 From: DongilMin Date: Fri, 27 Sep 2024 07:33:07 +0900 Subject: [PATCH 3/9] [Refactor/InhaBas#168] CookieUtilsTest Code Refactoring --- .../domain/oauth2/cookie/CookieUtilsTest.java | 138 ++++++++---------- 1 file changed, 57 insertions(+), 81 deletions(-) diff --git a/module-auth/src/test/java/com/inhabas/api/auth/domain/oauth2/cookie/CookieUtilsTest.java b/module-auth/src/test/java/com/inhabas/api/auth/domain/oauth2/cookie/CookieUtilsTest.java index 31af7b3b..01512620 100644 --- a/module-auth/src/test/java/com/inhabas/api/auth/domain/oauth2/cookie/CookieUtilsTest.java +++ b/module-auth/src/test/java/com/inhabas/api/auth/domain/oauth2/cookie/CookieUtilsTest.java @@ -1,43 +1,41 @@ package com.inhabas.api.auth.domain.oauth2.cookie; import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.jupiter.api.Assertions.assertTrue; - import java.lang.reflect.Constructor; -import java.lang.reflect.InvocationTargetException; import java.util.Optional; import java.util.Set; import javax.servlet.http.Cookie; +import org.apache.commons.codec.binary.Base64; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; import org.springframework.mock.web.MockHttpServletRequest; import org.springframework.mock.web.MockHttpServletResponse; import org.springframework.security.oauth2.core.AuthorizationGrantType; import org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationRequest; -import org.apache.commons.codec.binary.Base64; - -import org.junit.jupiter.api.DisplayName; -import org.junit.jupiter.api.Test; - public class CookieUtilsTest { + private static final String COOKIE_NAME = "myCookie"; + private static final String COOKIE_CONTENTS = "hello"; + private static final int COOKIE_MAX_AGE = 180; + @DisplayName("request 에서 쿠키를 꺼낸다.") @Test public void resolveCookieFromRequest() { // given - MockHttpServletRequest request = new MockHttpServletRequest(); - Cookie cookie = new Cookie("myCookie", "hello"); - cookie.setMaxAge(180); - request.setCookies(cookie); + MockHttpServletRequest request = createRequestWithCookie(COOKIE_NAME, COOKIE_CONTENTS, COOKIE_MAX_AGE); // when - Optional myCookie = CookieUtils.resolveCookie(request, "myCookie"); + Optional myCookie = CookieUtils.resolveCookie(request, COOKIE_NAME); // then - assertThat(myCookie.isPresent()).isTrue(); - assertThat(myCookie.get().getValue()).isEqualTo("hello"); - assertThat(myCookie.get().getMaxAge()).isEqualTo(180); + assertThat(myCookie).isPresent() + .hasValueSatisfying(cookie -> { + assertThat(cookie.getValue()).isEqualTo(COOKIE_CONTENTS); + assertThat(cookie.getMaxAge()).isEqualTo(COOKIE_MAX_AGE); + }); } @DisplayName("response 에 쿠키를 저장한다.") @@ -45,19 +43,18 @@ public void resolveCookieFromRequest() { public void saveCookieToResponse() { // given MockHttpServletResponse response = new MockHttpServletResponse(); - String cookieName = "myCookie"; - String cookieContents = "hello"; // when - CookieUtils.setCookie(response, cookieName, cookieContents, 180); + CookieUtils.setCookie(response, COOKIE_NAME, COOKIE_CONTENTS, COOKIE_MAX_AGE); // then - Cookie resolvedCookie = response.getCookie(cookieName); - assert resolvedCookie != null; - - assertThat(resolvedCookie.getName()).isEqualTo(cookieName); - assertThat(resolvedCookie.getValue()).isEqualTo(cookieContents); - assertThat(resolvedCookie.getMaxAge()).isEqualTo(180); + Cookie resolvedCookie = response.getCookie(COOKIE_NAME); + assertThat(resolvedCookie).isNotNull() + .satisfies(cookie -> { + assertThat(cookie.getName()).isEqualTo(COOKIE_NAME); + assertThat(cookie.getValue()).isEqualTo(COOKIE_CONTENTS); + assertThat(cookie.getMaxAge()).isEqualTo(COOKIE_MAX_AGE); + }); } @DisplayName("request 에서 쿠키를 지운다.") @@ -65,72 +62,61 @@ public void saveCookieToResponse() { public void removeCookieOfRequest() { // given MockHttpServletResponse response = new MockHttpServletResponse(); - MockHttpServletRequest request = new MockHttpServletRequest(); - Cookie cookie = new Cookie("myCookie", "hello"); - cookie.setMaxAge(180); - request.setCookies(cookie); + MockHttpServletRequest request = createRequestWithCookie(COOKIE_NAME, COOKIE_CONTENTS, COOKIE_MAX_AGE); // when - CookieUtils.deleteCookie(request, response, "myCookie"); + CookieUtils.deleteCookie(request, response, COOKIE_NAME); // then - Cookie deletedCookie = response.getCookie("myCookie"); - assert deletedCookie != null; - assertThat(deletedCookie.getMaxAge()).isEqualTo(0); - assertThat(deletedCookie.getValue()).isEqualTo(""); + Cookie deletedCookie = response.getCookie(COOKIE_NAME); + assertThat(deletedCookie).isNotNull() + .satisfies(cookie -> { + assertThat(cookie.getMaxAge()).isEqualTo(0); + assertThat(cookie.getValue()).isEqualTo(""); + }); } @DisplayName("성공적으로 serialize 한다.") @Test - public void serializingTest() - throws InvocationTargetException, InstantiationException, IllegalAccessException, - NoSuchMethodException { - // reflection - Constructor constructor = - OAuth2AuthorizationRequest.Builder.class.getDeclaredConstructor( - AuthorizationGrantType.class); - constructor.setAccessible(true); - - // given - OAuth2AuthorizationRequest.Builder builder = - (OAuth2AuthorizationRequest.Builder) - constructor.newInstance(AuthorizationGrantType.AUTHORIZATION_CODE); - OAuth2AuthorizationRequest request = - builder - .authorizationUri("https://kauth.kakao.com/oauth/authorize") - .clientId("1234") - .redirectUri("http://localhost/api/login/oauth2/code/kakao") - .scopes(Set.of("gender", "profile_image", "account_email", "profile_nickname")) - .state("state1934") - .additionalParameters(java.util.Map.of()) - .attributes(java.util.Map.of("registration_id", "kakao")) - .build(); + public void serializingTest() throws Exception { + OAuth2AuthorizationRequest request = createOAuth2AuthorizationRequest(); // when String serializedRequest = CookieUtils.serialize(request); // then - assertTrue(Base64.isBase64(serializedRequest)); + assertThat(serializedRequest).matches(Base64::isBase64); } @DisplayName("성공적으로 deserialize 한다.") @Test - public void deserializingTest() - throws NoSuchMethodException, InvocationTargetException, InstantiationException, - IllegalAccessException { + public void deserializingTest() throws Exception { + OAuth2AuthorizationRequest originalRequest = createOAuth2AuthorizationRequest(); + String serializedRequest = CookieUtils.serialize(originalRequest); + Cookie cookie = new Cookie("base64", serializedRequest); + + // when + OAuth2AuthorizationRequest deserializedRequest = CookieUtils.deserialize(cookie, OAuth2AuthorizationRequest.class); + + // then + assertThat(deserializedRequest).usingRecursiveComparison().isEqualTo(originalRequest); + } + + private MockHttpServletRequest createRequestWithCookie(String name, String value, int maxAge) { + MockHttpServletRequest request = new MockHttpServletRequest(); + Cookie cookie = new Cookie(name, value); + cookie.setMaxAge(maxAge); + request.setCookies(cookie); + return request; + } + static private OAuth2AuthorizationRequest createOAuth2AuthorizationRequest() throws Exception { // reflection - Constructor constructor = - OAuth2AuthorizationRequest.Builder.class.getDeclaredConstructor( - AuthorizationGrantType.class); + Constructor constructor = OAuth2AuthorizationRequest.Builder.class.getDeclaredConstructor(AuthorizationGrantType.class); constructor.setAccessible(true); - // given - OAuth2AuthorizationRequest.Builder builder = - (OAuth2AuthorizationRequest.Builder) - constructor.newInstance(AuthorizationGrantType.AUTHORIZATION_CODE); - OAuth2AuthorizationRequest originalRequest = - builder + OAuth2AuthorizationRequest.Builder builder = (OAuth2AuthorizationRequest.Builder) constructor.newInstance(AuthorizationGrantType.AUTHORIZATION_CODE); + return builder .authorizationUri("https://kauth.kakao.com/oauth/authorize") .clientId("1234") .redirectUri("http://localhost/api/login/oauth2/code/kakao") @@ -139,15 +125,5 @@ public void deserializingTest() .additionalParameters(java.util.Map.of()) .attributes(java.util.Map.of("registration_id", "kakao")) .build(); - - String serializedRequest = CookieUtils.serialize(originalRequest); - Cookie cookie = new Cookie("base64", serializedRequest); - - // when - OAuth2AuthorizationRequest deserializedRequest = - CookieUtils.deserialize(cookie, OAuth2AuthorizationRequest.class); - - // then - assertThat(deserializedRequest).usingRecursiveComparison().isEqualTo(originalRequest); } -} +} \ No newline at end of file From 1f6732bd155e978833da20c3d9a7d10cee7d00b8 Mon Sep 17 00:00:00 2001 From: DongilMin Date: Fri, 4 Oct 2024 01:25:09 +0900 Subject: [PATCH 4/9] [Refactor/InhaBas#168]CookieUtilsTest Code Refactoring --- .../domain/oauth2/cookie/CookieUtilsTest.java | 77 ++++++++++++------- 1 file changed, 50 insertions(+), 27 deletions(-) diff --git a/module-auth/src/test/java/com/inhabas/api/auth/domain/oauth2/cookie/CookieUtilsTest.java b/module-auth/src/test/java/com/inhabas/api/auth/domain/oauth2/cookie/CookieUtilsTest.java index 01512620..93fec143 100644 --- a/module-auth/src/test/java/com/inhabas/api/auth/domain/oauth2/cookie/CookieUtilsTest.java +++ b/module-auth/src/test/java/com/inhabas/api/auth/domain/oauth2/cookie/CookieUtilsTest.java @@ -1,20 +1,24 @@ package com.inhabas.api.auth.domain.oauth2.cookie; import static org.assertj.core.api.Assertions.assertThat; + import java.lang.reflect.Constructor; +import java.lang.reflect.InvocationTargetException; import java.util.Optional; import java.util.Set; import javax.servlet.http.Cookie; -import org.apache.commons.codec.binary.Base64; -import org.junit.jupiter.api.DisplayName; -import org.junit.jupiter.api.Test; import org.springframework.mock.web.MockHttpServletRequest; import org.springframework.mock.web.MockHttpServletResponse; import org.springframework.security.oauth2.core.AuthorizationGrantType; import org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationRequest; +import org.apache.commons.codec.binary.Base64; + +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + public class CookieUtilsTest { private static final String COOKIE_NAME = "myCookie"; @@ -25,14 +29,17 @@ public class CookieUtilsTest { @Test public void resolveCookieFromRequest() { // given - MockHttpServletRequest request = createRequestWithCookie(COOKIE_NAME, COOKIE_CONTENTS, COOKIE_MAX_AGE); + MockHttpServletRequest request = + createRequestWithCookie(COOKIE_NAME, COOKIE_CONTENTS, COOKIE_MAX_AGE); // when Optional myCookie = CookieUtils.resolveCookie(request, COOKIE_NAME); // then - assertThat(myCookie).isPresent() - .hasValueSatisfying(cookie -> { + assertThat(myCookie) + .isPresent() + .hasValueSatisfying( + cookie -> { assertThat(cookie.getValue()).isEqualTo(COOKIE_CONTENTS); assertThat(cookie.getMaxAge()).isEqualTo(COOKIE_MAX_AGE); }); @@ -49,8 +56,10 @@ public void saveCookieToResponse() { // then Cookie resolvedCookie = response.getCookie(COOKIE_NAME); - assertThat(resolvedCookie).isNotNull() - .satisfies(cookie -> { + assertThat(resolvedCookie) + .isNotNull() + .satisfies( + cookie -> { assertThat(cookie.getName()).isEqualTo(COOKIE_NAME); assertThat(cookie.getValue()).isEqualTo(COOKIE_CONTENTS); assertThat(cookie.getMaxAge()).isEqualTo(COOKIE_MAX_AGE); @@ -62,23 +71,28 @@ public void saveCookieToResponse() { public void removeCookieOfRequest() { // given MockHttpServletResponse response = new MockHttpServletResponse(); - MockHttpServletRequest request = createRequestWithCookie(COOKIE_NAME, COOKIE_CONTENTS, COOKIE_MAX_AGE); + MockHttpServletRequest request = + createRequestWithCookie(COOKIE_NAME, COOKIE_CONTENTS, COOKIE_MAX_AGE); // when CookieUtils.deleteCookie(request, response, COOKIE_NAME); // then Cookie deletedCookie = response.getCookie(COOKIE_NAME); - assertThat(deletedCookie).isNotNull() - .satisfies(cookie -> { + assertThat(deletedCookie) + .isNotNull() + .satisfies( + cookie -> { assertThat(cookie.getMaxAge()).isEqualTo(0); - assertThat(cookie.getValue()).isEqualTo(""); + assertThat(cookie.getValue()).isEmpty(); }); } @DisplayName("성공적으로 serialize 한다.") @Test - public void serializingTest() throws Exception { + public void serializingTest() + throws NoSuchMethodException, InvocationTargetException, InstantiationException, + IllegalAccessException { OAuth2AuthorizationRequest request = createOAuth2AuthorizationRequest(); // when @@ -90,13 +104,16 @@ public void serializingTest() throws Exception { @DisplayName("성공적으로 deserialize 한다.") @Test - public void deserializingTest() throws Exception { + public void deserializingTest() + throws NoSuchMethodException, InvocationTargetException, InstantiationException, + IllegalAccessException { OAuth2AuthorizationRequest originalRequest = createOAuth2AuthorizationRequest(); String serializedRequest = CookieUtils.serialize(originalRequest); Cookie cookie = new Cookie("base64", serializedRequest); // when - OAuth2AuthorizationRequest deserializedRequest = CookieUtils.deserialize(cookie, OAuth2AuthorizationRequest.class); + OAuth2AuthorizationRequest deserializedRequest = + CookieUtils.deserialize(cookie, OAuth2AuthorizationRequest.class); // then assertThat(deserializedRequest).usingRecursiveComparison().isEqualTo(originalRequest); @@ -110,20 +127,26 @@ private MockHttpServletRequest createRequestWithCookie(String name, String value return request; } - static private OAuth2AuthorizationRequest createOAuth2AuthorizationRequest() throws Exception { + private static OAuth2AuthorizationRequest createOAuth2AuthorizationRequest() + throws NoSuchMethodException, InvocationTargetException, InstantiationException, + IllegalAccessException { // reflection - Constructor constructor = OAuth2AuthorizationRequest.Builder.class.getDeclaredConstructor(AuthorizationGrantType.class); + Constructor constructor = + OAuth2AuthorizationRequest.Builder.class.getDeclaredConstructor( + AuthorizationGrantType.class); constructor.setAccessible(true); - OAuth2AuthorizationRequest.Builder builder = (OAuth2AuthorizationRequest.Builder) constructor.newInstance(AuthorizationGrantType.AUTHORIZATION_CODE); + OAuth2AuthorizationRequest.Builder builder = + (OAuth2AuthorizationRequest.Builder) + constructor.newInstance(AuthorizationGrantType.AUTHORIZATION_CODE); return builder - .authorizationUri("https://kauth.kakao.com/oauth/authorize") - .clientId("1234") - .redirectUri("http://localhost/api/login/oauth2/code/kakao") - .scopes(Set.of("gender", "profile_image", "account_email", "profile_nickname")) - .state("state1934") - .additionalParameters(java.util.Map.of()) - .attributes(java.util.Map.of("registration_id", "kakao")) - .build(); + .authorizationUri("https://kauth.kakao.com/oauth/authorize") + .clientId("1234") + .redirectUri("http://localhost/api/login/oauth2/code/kakao") + .scopes(Set.of("gender", "profile_image", "account_email", "profile_nickname")) + .state("state1934") + .additionalParameters(java.util.Map.of()) + .attributes(java.util.Map.of("registration_id", "kakao")) + .build(); } -} \ No newline at end of file +} From f0b611cc030bb025351d311e6e89e715442f1d31 Mon Sep 17 00:00:00 2001 From: DongilMin Date: Fri, 4 Oct 2024 05:41:18 +0900 Subject: [PATCH 5/9] Refactoring OAuth2AuthorizationRequestRepositoryTest --- ...th2AuthorizationRequestRepositoryTest.java | 36 ++++++++++--------- 1 file changed, 20 insertions(+), 16 deletions(-) diff --git a/module-auth/src/test/java/com/inhabas/api/auth/domain/oauth2/cookie/HttpCookieOAuth2AuthorizationRequestRepositoryTest.java b/module-auth/src/test/java/com/inhabas/api/auth/domain/oauth2/cookie/HttpCookieOAuth2AuthorizationRequestRepositoryTest.java index 1c8677a7..5c4410bd 100644 --- a/module-auth/src/test/java/com/inhabas/api/auth/domain/oauth2/cookie/HttpCookieOAuth2AuthorizationRequestRepositoryTest.java +++ b/module-auth/src/test/java/com/inhabas/api/auth/domain/oauth2/cookie/HttpCookieOAuth2AuthorizationRequestRepositoryTest.java @@ -3,7 +3,6 @@ import static com.inhabas.api.auth.domain.oauth2.cookie.HttpCookieOAuth2AuthorizationRequestRepository.OAUTH2_AUTHORIZATION_REQUEST_COOKIE_NAME; import static com.inhabas.api.auth.domain.oauth2.cookie.HttpCookieOAuth2AuthorizationRequestRepository.REDIRECT_URL_PARAM_COOKIE_NAME; import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.jupiter.api.Assertions.assertTrue; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; @@ -19,11 +18,19 @@ import org.apache.commons.codec.binary.Base64; +import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; public class HttpCookieOAuth2AuthorizationRequestRepositoryTest { + private HttpCookieOAuth2AuthorizationRequestRepository repository; + + @BeforeEach + public void setUp() { + repository = new HttpCookieOAuth2AuthorizationRequestRepository(); + } + private final HttpCookieOAuth2AuthorizationRequestRepository httpCookieOAuth2AuthorizationRequestRepository = new HttpCookieOAuth2AuthorizationRequestRepository(); @@ -62,8 +69,7 @@ public void saveAuthorizationRequestNullTest() { MockHttpServletResponse response = new MockHttpServletResponse(); // when - httpCookieOAuth2AuthorizationRequestRepository.saveAuthorizationRequest( - null, request, response); + repository.saveAuthorizationRequest(null, request, response); // then assertThat(response.getCookies()) @@ -83,14 +89,13 @@ public void saveAuthorizationRequestTest() throws NoSuchMethodException { OAuth2AuthorizationRequest oAuth2AuthorizationRequest = this.createOAuth2AuthorizationRequest(); // when - httpCookieOAuth2AuthorizationRequestRepository.saveAuthorizationRequest( - oAuth2AuthorizationRequest, request, response); + repository.saveAuthorizationRequest(oAuth2AuthorizationRequest, request, response); // then // 쿠키 한가지 존재하는지 확인. Cookie savedCookie = response.getCookie(OAUTH2_AUTHORIZATION_REQUEST_COOKIE_NAME); - assert savedCookie != null; - assertTrue(Base64.isBase64(savedCookie.getValue())); + assertThat(savedCookie).isNotNull(); + assertThat(Base64.isBase64(savedCookie.getValue())).isTrue(); } @DisplayName("OAuth2AuthorizationRequest 를 쿠키로 저장할 때, redirect_url 도 쿠키로 저장한다.") @@ -104,8 +109,7 @@ public void saveAuthorizationRequestWithRedirectUrlTest() throws NoSuchMethodExc request.setParameter(REDIRECT_URL_PARAM_COOKIE_NAME, "/index.html"); // when - httpCookieOAuth2AuthorizationRequestRepository.saveAuthorizationRequest( - oAuth2AuthorizationRequest, request, response); + repository.saveAuthorizationRequest(oAuth2AuthorizationRequest, request, response); // then // 쿠키 두가지 존재하는 지 확인 @@ -133,13 +137,13 @@ public void removeAuthorizationRequestTest() throws NoSuchMethodException { // when OAuth2AuthorizationRequest returnedRequest = - httpCookieOAuth2AuthorizationRequestRepository.removeAuthorizationRequest( - request, response); + repository.removeAuthorizationRequest(request, response); // then Cookie cookie = response.getCookie(OAUTH2_AUTHORIZATION_REQUEST_COOKIE_NAME); - assert cookie != null; - assertTrue(cookie.getValue().isBlank() && cookie.getMaxAge() == 0); + assertThat(cookie).isNotNull(); + assertThat(cookie.getValue()).isBlank(); + assertThat(cookie.getMaxAge()).isEqualTo(0); } @DisplayName("OAuth2AuthorizationRequest 를 성공적으로 쿠키에서 삭제한다. (redirectUrl 쿠키도 삭제된다.)") @@ -150,7 +154,7 @@ public void removeAuthorizationRequestTotally() { MockHttpServletResponse response = new MockHttpServletResponse(); // when - httpCookieOAuth2AuthorizationRequestRepository.clearCookies(request, response); + repository.clearCookies(request, response); // then assertThat(response.getCookies()) @@ -189,8 +193,8 @@ private OAuth2AuthorizationRequest createOAuth2AuthorizationRequest() .attributes(java.util.Map.of("registration_id", "kakao")) .build(); - } catch (InvocationTargetException | InstantiationException | IllegalAccessException ignored) { - return null; + } catch (InvocationTargetException | InstantiationException | IllegalAccessException e) { + throw new RuntimeException("Failed to create OAuth2AuthorizationRequest", e); } } } From fab5f1c1b4884010aabc92088298402a12b9b248 Mon Sep 17 00:00:00 2001 From: DongilMin Date: Mon, 28 Oct 2024 17:40:45 +0900 Subject: [PATCH 6/9] handler_Failure Test Code Refatoring --- ...auth2AuthenticationFailureHandlerTest.java | 43 +++++++++++-------- 1 file changed, 26 insertions(+), 17 deletions(-) diff --git a/module-auth/src/test/java/com/inhabas/api/auth/domain/oauth2/handler/Oauth2AuthenticationFailureHandlerTest.java b/module-auth/src/test/java/com/inhabas/api/auth/domain/oauth2/handler/Oauth2AuthenticationFailureHandlerTest.java index b1440535..c5cf4467 100644 --- a/module-auth/src/test/java/com/inhabas/api/auth/domain/oauth2/handler/Oauth2AuthenticationFailureHandlerTest.java +++ b/module-auth/src/test/java/com/inhabas/api/auth/domain/oauth2/handler/Oauth2AuthenticationFailureHandlerTest.java @@ -38,53 +38,62 @@ public class Oauth2AuthenticationFailureHandlerTest { @Mock private AuthProperties.OAuth2 oauth2Utils; + + private static final String VALID_REDIRECT_URL = "https://www.inhabas.com"; + private static final String INVALID_REDIRECT_URL = "https://www.unauthorized_url.com"; + private static final String ERROR_CODE = OAuth2ErrorCodes.INVALID_REQUEST; + @BeforeEach public void setUp() { given(authProperties.getOauth2()).willReturn(oauth2Utils); } + private MockHttpServletRequest createRequestWithCookie(String cookieValue) { + MockHttpServletRequest request = new MockHttpServletRequest(); + Cookie redirectCookie = new Cookie(REDIRECT_URL_PARAM_COOKIE_NAME, cookieValue); + request.setCookies(redirectCookie); + return request; + } + + private AuthenticationException createAuthenticationException(String errorCode) { + return new OAuth2AuthenticationException(errorCode); + } + + @DisplayName("FailureHandler 호출 시, 허락된 defaultURL 로 정상적으로 리다이렉트 된다.") @Test public void redirectToDefaultTest() throws IOException { // given - String errorCode = OAuth2ErrorCodes.INVALID_REQUEST; - MockHttpServletRequest request = new MockHttpServletRequest(); + MockHttpServletRequest request = createRequestWithCookie(VALID_REDIRECT_URL); MockHttpServletResponse response = new MockHttpServletResponse(); - AuthenticationException authenticationException = new OAuth2AuthenticationException(errorCode); - - Cookie redirectCookie = new Cookie(REDIRECT_URL_PARAM_COOKIE_NAME, "https://www.inhabas.com"); - request.setCookies(redirectCookie); + AuthenticationException authenticationException = new OAuth2AuthenticationException(ERROR_CODE); - given(oauth2Utils.getDefaultRedirectUri()).willReturn("https://www.inhabas.com"); + given(oauth2Utils.getDefaultRedirectUri()).willReturn(VALID_REDIRECT_URL); // when oauth2AuthenticationFailureHandler.onAuthenticationFailure( request, response, authenticationException); // then - assertThat(response.getRedirectedUrl()).isEqualTo("https://www.inhabas.com?error=" + errorCode); + assertThat(response.getRedirectedUrl()).isEqualTo(VALID_REDIRECT_URL + "?error=" + ERROR_CODE); + } @DisplayName("유효하지 않은 redirect_url 은 허용하지 않는다.") @Test public void validateRedirectUrlTest() throws IOException { // given - String errorCode = OAuth2ErrorCodes.INVALID_REQUEST; - MockHttpServletRequest request = new MockHttpServletRequest(); + MockHttpServletRequest request = createRequestWithCookie(INVALID_REDIRECT_URL); MockHttpServletResponse response = new MockHttpServletResponse(); - AuthenticationException authenticationException = new OAuth2AuthenticationException(errorCode); - - Cookie redirectCookie = - new Cookie(REDIRECT_URL_PARAM_COOKIE_NAME, "https://www.unauthorized_url.com"); - request.setCookies(redirectCookie); + AuthenticationException authenticationException = createAuthenticationException(ERROR_CODE); - given(oauth2Utils.getDefaultRedirectUri()).willReturn("https://www.inhabas.com"); + given(oauth2Utils.getDefaultRedirectUri()).willReturn(VALID_REDIRECT_URL); // when oauth2AuthenticationFailureHandler.onAuthenticationFailure( request, response, authenticationException); // then - assertThat(response.getRedirectedUrl()).isEqualTo("https://www.inhabas.com?error=" + errorCode); + assertThat(response.getRedirectedUrl()).isEqualTo(VALID_REDIRECT_URL + "?error=" + ERROR_CODE); } } From 2d2a9b6c40eb7fa28abcd0803b67526e00bc71ec Mon Sep 17 00:00:00 2001 From: DongilMin Date: Mon, 28 Oct 2024 18:11:59 +0900 Subject: [PATCH 7/9] Oauth2AuthenticationSuccessHandlerTest.java Test Code Refactoring --- ...auth2AuthenticationSuccessHandlerTest.java | 41 ++++++++++--------- 1 file changed, 21 insertions(+), 20 deletions(-) diff --git a/module-auth/src/test/java/com/inhabas/api/auth/domain/oauth2/handler/Oauth2AuthenticationSuccessHandlerTest.java b/module-auth/src/test/java/com/inhabas/api/auth/domain/oauth2/handler/Oauth2AuthenticationSuccessHandlerTest.java index 2bfaffcc..d481f6b4 100644 --- a/module-auth/src/test/java/com/inhabas/api/auth/domain/oauth2/handler/Oauth2AuthenticationSuccessHandlerTest.java +++ b/module-auth/src/test/java/com/inhabas/api/auth/domain/oauth2/handler/Oauth2AuthenticationSuccessHandlerTest.java @@ -51,6 +51,8 @@ public class Oauth2AuthenticationSuccessHandlerTest { private final Set basicAuthorities = Collections.singleton(new SimpleGrantedAuthority("ROLE_BASIC")); + private static final String VALID_REDIRECT_URL = "https://www.inhabas.com"; + @BeforeEach public void setUp() { given(authProperties.getOauth2()).willReturn(oAuth2Utils); @@ -58,18 +60,25 @@ public void setUp() { new DefaultOAuth2User(basicAuthorities, Map.of("id", 1234, "properties", "blahblah"), "id"); } + private MockHttpServletRequest createRequestWithCookie(String cookieValue) { + MockHttpServletRequest request = new MockHttpServletRequest(); + Cookie redirectCookie = new Cookie(REDIRECT_URL_PARAM_COOKIE_NAME, cookieValue); + request.setCookies(redirectCookie); + return request; + } + + private OAuth2AuthenticationToken createAuthenticationToken() { + return new OAuth2AuthenticationToken(defaultOAuth2User, basicAuthorities, "google"); + } + @DisplayName("SuccessHandler 호출 시, targetURL 로 정상적으로 리다이렉트 된다.") @Test public void redirectToTargetUrlTest() throws IOException { // given - MockHttpServletRequest request = new MockHttpServletRequest(); + MockHttpServletRequest request = createRequestWithCookie(VALID_REDIRECT_URL); MockHttpServletResponse response = new MockHttpServletResponse(); - OAuth2AuthenticationToken authenticationToken = - new OAuth2AuthenticationToken(defaultOAuth2User, basicAuthorities, "google"); - - Cookie redirectCookie = new Cookie(REDIRECT_URL_PARAM_COOKIE_NAME, "https://www.inhabas.com"); - request.setCookies(redirectCookie); + OAuth2AuthenticationToken authenticationToken = createAuthenticationToken(); given(oAuth2Utils.isAuthorizedRedirectUri(any())).willReturn(true); @@ -79,7 +88,7 @@ public void redirectToTargetUrlTest() throws IOException { // then assertThat(response.getRedirectedUrl()) .contains( - "https://www.inhabas.com", "accessToken", "refreshToken", "expiresIn", "imageUrl"); + VALID_REDIRECT_URL, "accessToken", "refreshToken", "expiresIn", "imageUrl"); } @DisplayName("인가되지 않은 redirect_url 요청 시, UnauthorizedRedirectUriException 발생") @@ -87,13 +96,9 @@ public void redirectToTargetUrlTest() throws IOException { public void unAuthorizedTargetUrlTest() { // given - MockHttpServletRequest request = new MockHttpServletRequest(); + MockHttpServletRequest request = createRequestWithCookie(VALID_REDIRECT_URL); MockHttpServletResponse response = new MockHttpServletResponse(); - OAuth2AuthenticationToken authenticationToken = - new OAuth2AuthenticationToken(defaultOAuth2User, basicAuthorities, "google"); - - Cookie redirectCookie = new Cookie(REDIRECT_URL_PARAM_COOKIE_NAME, "https://www.inhabas.com"); - request.setCookies(redirectCookie); + OAuth2AuthenticationToken authenticationToken = createAuthenticationToken(); given(oAuth2Utils.isAuthorizedRedirectUri(any())).willReturn(false); @@ -107,20 +112,16 @@ public void unAuthorizedTargetUrlTest() { @Test public void clearCookieAfterHandleOAuth2Authentication() throws IOException { // given - MockHttpServletRequest request = new MockHttpServletRequest(); + MockHttpServletRequest request = createRequestWithCookie(VALID_REDIRECT_URL); MockHttpServletResponse response = new MockHttpServletResponse(); - OAuth2AuthenticationToken authenticationToken = - new OAuth2AuthenticationToken(defaultOAuth2User, basicAuthorities, "google"); - - Cookie redirectCookie = new Cookie(REDIRECT_URL_PARAM_COOKIE_NAME, "https://www.inhabas.com"); - request.setCookies(redirectCookie); + OAuth2AuthenticationToken authenticationToken = createAuthenticationToken(); given(oAuth2Utils.isAuthorizedRedirectUri(any())).willReturn(true); // when successHandler.onAuthenticationSuccess(request, response, authenticationToken); - // when + // then then(requestRepository).should(times(1)).clearCookies(any(), any()); } } From 3b3211dd6f54e5c7fdab52b87166e63635d417a4 Mon Sep 17 00:00:00 2001 From: DongilMin Date: Mon, 28 Oct 2024 18:35:20 +0900 Subject: [PATCH 8/9] =?UTF-8?q?[feature/#02]=20cookie,=20handler=20?= =?UTF-8?q?=EB=94=94=EB=A0=89=ED=86=A0=EB=A6=AC=20=ED=85=8C=EC=8A=A4?= =?UTF-8?q?=ED=8A=B8=EC=BD=94=EB=93=9C=20=EB=A6=AC=ED=8C=A9=ED=86=A0?= =?UTF-8?q?=EB=A7=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../oauth2/handler/Oauth2AuthenticationFailureHandlerTest.java | 3 --- .../oauth2/handler/Oauth2AuthenticationSuccessHandlerTest.java | 3 +-- 2 files changed, 1 insertion(+), 5 deletions(-) diff --git a/module-auth/src/test/java/com/inhabas/api/auth/domain/oauth2/handler/Oauth2AuthenticationFailureHandlerTest.java b/module-auth/src/test/java/com/inhabas/api/auth/domain/oauth2/handler/Oauth2AuthenticationFailureHandlerTest.java index c5cf4467..497ade15 100644 --- a/module-auth/src/test/java/com/inhabas/api/auth/domain/oauth2/handler/Oauth2AuthenticationFailureHandlerTest.java +++ b/module-auth/src/test/java/com/inhabas/api/auth/domain/oauth2/handler/Oauth2AuthenticationFailureHandlerTest.java @@ -38,7 +38,6 @@ public class Oauth2AuthenticationFailureHandlerTest { @Mock private AuthProperties.OAuth2 oauth2Utils; - private static final String VALID_REDIRECT_URL = "https://www.inhabas.com"; private static final String INVALID_REDIRECT_URL = "https://www.unauthorized_url.com"; private static final String ERROR_CODE = OAuth2ErrorCodes.INVALID_REQUEST; @@ -59,7 +58,6 @@ private AuthenticationException createAuthenticationException(String errorCode) return new OAuth2AuthenticationException(errorCode); } - @DisplayName("FailureHandler 호출 시, 허락된 defaultURL 로 정상적으로 리다이렉트 된다.") @Test public void redirectToDefaultTest() throws IOException { @@ -76,7 +74,6 @@ public void redirectToDefaultTest() throws IOException { // then assertThat(response.getRedirectedUrl()).isEqualTo(VALID_REDIRECT_URL + "?error=" + ERROR_CODE); - } @DisplayName("유효하지 않은 redirect_url 은 허용하지 않는다.") diff --git a/module-auth/src/test/java/com/inhabas/api/auth/domain/oauth2/handler/Oauth2AuthenticationSuccessHandlerTest.java b/module-auth/src/test/java/com/inhabas/api/auth/domain/oauth2/handler/Oauth2AuthenticationSuccessHandlerTest.java index d481f6b4..a10af762 100644 --- a/module-auth/src/test/java/com/inhabas/api/auth/domain/oauth2/handler/Oauth2AuthenticationSuccessHandlerTest.java +++ b/module-auth/src/test/java/com/inhabas/api/auth/domain/oauth2/handler/Oauth2AuthenticationSuccessHandlerTest.java @@ -87,8 +87,7 @@ public void redirectToTargetUrlTest() throws IOException { // then assertThat(response.getRedirectedUrl()) - .contains( - VALID_REDIRECT_URL, "accessToken", "refreshToken", "expiresIn", "imageUrl"); + .contains(VALID_REDIRECT_URL, "accessToken", "refreshToken", "expiresIn", "imageUrl"); } @DisplayName("인가되지 않은 redirect_url 요청 시, UnauthorizedRedirectUriException 발생") From d06d5b94b482456ffe06c6dbdf4675d8fd01f55f Mon Sep 17 00:00:00 2001 From: DongilMin Date: Sun, 3 Nov 2024 18:37:37 +0900 Subject: [PATCH 9/9] =?UTF-8?q?CollgeTest.java,=20MajorTest.java,=20MajorI?= =?UTF-8?q?nfoServiceTest.java=20=ED=85=8C=EC=8A=A4=ED=8A=B8=20=EC=BD=94?= =?UTF-8?q?=EB=93=9C=20=EB=A6=AC=ED=8C=A9=ED=86=A0=EB=A7=81,=20=EB=A9=94?= =?UTF-8?q?=EC=84=9C=EB=93=9C=20=EC=9D=B4=EB=A6=84=20=EA=B0=9C=EC=84=A0,?= =?UTF-8?q?=20=EA=B0=80=EB=8F=85=EC=84=B1=20=ED=96=A5=EC=83=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../domain/valueObject/CollegeTest.java | 8 ++--- .../domain/valueObject/MajorTest.java | 8 ++--- .../usecase/MajorInfoServiceTest.java | 34 +++++++++---------- 3 files changed, 24 insertions(+), 26 deletions(-) diff --git a/module-auth/src/test/java/com/inhabas/api/auth/domain/oauth2/majorInfo/domain/valueObject/CollegeTest.java b/module-auth/src/test/java/com/inhabas/api/auth/domain/oauth2/majorInfo/domain/valueObject/CollegeTest.java index cf8ddd24..c0efb470 100644 --- a/module-auth/src/test/java/com/inhabas/api/auth/domain/oauth2/majorInfo/domain/valueObject/CollegeTest.java +++ b/module-auth/src/test/java/com/inhabas/api/auth/domain/oauth2/majorInfo/domain/valueObject/CollegeTest.java @@ -12,7 +12,7 @@ public class CollegeTest { @DisplayName("College 타입에 제목을 저장한다.") @Test - public void College_is_OK() { + public void saveValidCollegeName() { // given String collegeString = "사회과학대학"; @@ -26,7 +26,7 @@ public void College_is_OK() { @DisplayName("College 타입에 너무 긴 이름을 저장한다. 20자 이상") @Test - public void College_is_too_long() { + public void throwExceptionWhenSavingTooLongCollegeName() { // given String collegeString = "지금이문장은10자임".repeat(20); @@ -37,14 +37,14 @@ public void College_is_too_long() { @DisplayName("College 은 null 일 수 없습니다.") @Test - public void College_cannot_be_Null() { + public void throwExceptionWhenSavingNullCollegeName() { assertThrows(InvalidInputException.class, () -> new College(null)); } @DisplayName("College 은 빈 문자열일 수 없습니다.") @Test - public void College_cannot_be_Blank() { + public void throwExceptionWhenSavingBlankCollegeName() { assertThrows(InvalidInputException.class, () -> new College("\t")); } diff --git a/module-auth/src/test/java/com/inhabas/api/auth/domain/oauth2/majorInfo/domain/valueObject/MajorTest.java b/module-auth/src/test/java/com/inhabas/api/auth/domain/oauth2/majorInfo/domain/valueObject/MajorTest.java index 5f7e74fa..dd72dcec 100644 --- a/module-auth/src/test/java/com/inhabas/api/auth/domain/oauth2/majorInfo/domain/valueObject/MajorTest.java +++ b/module-auth/src/test/java/com/inhabas/api/auth/domain/oauth2/majorInfo/domain/valueObject/MajorTest.java @@ -12,7 +12,7 @@ public class MajorTest { @DisplayName("Major 타입에 제목을 저장한다.") @Test - public void Major_is_OK() { + public void saveValidMajorName() { // given String majorString = "컴퓨터공학과"; @@ -26,7 +26,7 @@ public void Major_is_OK() { @DisplayName("Major 타입에 너무 긴 이름을 저장한다. 50자 이상") @Test - public void Major_is_too_long() { + public void throwExceptionWhenSavingTooLongMajorName() { // given String majorString = "지금이문장은10자임".repeat(50); @@ -37,14 +37,14 @@ public void Major_is_too_long() { @DisplayName("Major 은 null 일 수 없습니다.") @Test - public void Major_cannot_be_Null() { + public void throwExceptionWhenSavingNullMajorName() { assertThrows(InvalidInputException.class, () -> new Major(null)); } @DisplayName("Major 은 빈 문자열일 수 없습니다.") @Test - public void Major_cannot_be_Blank() { + public void throwExceptionWhenSavingBlankMajorName() { assertThrows(InvalidInputException.class, () -> new Major("\t")); } diff --git a/module-auth/src/test/java/com/inhabas/api/auth/domain/oauth2/majorInfo/usecase/MajorInfoServiceTest.java b/module-auth/src/test/java/com/inhabas/api/auth/domain/oauth2/majorInfo/usecase/MajorInfoServiceTest.java index d23eac87..bbb4c759 100644 --- a/module-auth/src/test/java/com/inhabas/api/auth/domain/oauth2/majorInfo/usecase/MajorInfoServiceTest.java +++ b/module-auth/src/test/java/com/inhabas/api/auth/domain/oauth2/majorInfo/usecase/MajorInfoServiceTest.java @@ -9,7 +9,6 @@ import static org.mockito.Mockito.doNothing; import static org.mockito.Mockito.times; -import java.util.ArrayList; import java.util.List; import org.springframework.test.util.ReflectionTestUtils; @@ -33,26 +32,25 @@ public class MajorInfoServiceTest { @Mock private MajorInfoRepository majorInfoRepository; + private List createSampleMajorInfos() { + MajorInfo majorInfo1 = createMajorInfo("공과대학", "기계공학과", 1); + MajorInfo majorInfo2 = createMajorInfo("자연과학대학", "수학과", 2); + MajorInfo majorInfo3 = createMajorInfo("경영대학", "경영학과", 3); + return List.of(majorInfo1, majorInfo2, majorInfo3); + } + + private MajorInfo createMajorInfo(String college, String major, int id) { + MajorInfo majorInfo = new MajorInfo(college, major); + ReflectionTestUtils.setField(majorInfo, "id", id); + return majorInfo; + } + @DisplayName("모든 학과 정보를 불러온다.") @Test - public void findAllTest() { + public void getAllMajorInfoTest() { // given - MajorInfo majorInfo1 = new MajorInfo("공과대학", "기계공학과"); - MajorInfo majorInfo2 = new MajorInfo("자연과학대학", "수학과"); - MajorInfo majorInfo3 = new MajorInfo("경영대학", "경영학과"); - ReflectionTestUtils.setField(majorInfo1, "id", 1); - ReflectionTestUtils.setField(majorInfo2, "id", 2); - ReflectionTestUtils.setField(majorInfo3, "id", 3); - List majorInfos = - new ArrayList<>() { - { - add(majorInfo1); - add(majorInfo2); - add(majorInfo3); - } - }; - + List majorInfos = createSampleMajorInfos(); given(majorInfoRepository.findAll()).willReturn(majorInfos); // when @@ -68,7 +66,7 @@ public void findAllTest() { @DisplayName("새로운 학과를 추가한다.") @Test - public void saveMajorInfoTest() { + public void saveNewMajorInfoTest() { // given MajorInfoSaveDto newMajor = new MajorInfoSaveDto("경영대학", "글로벌금융학과");