Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -87,7 +87,7 @@ public CustomOAuth2AuthorizationRequestResolver customOAuth2AuthorizationRequest
) {
return new CustomOAuth2AuthorizationRequestResolver(
clientRegistrationRepository,
"/oauth2/authorization",
"/api/v1/oauth2/authorization",
redirectUriPolicy
);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ public class MemberController {
private final TokenService tokenService;
private final LoginCodeStore loginCodeStore;

@PostMapping("/logout")
@PostMapping("/api/v1/auth/logout")
@Operation(summary = "로그아웃", description = "로그아웃을 진행합니다.")
public ResponseEntity<ApiResponse<String>> logout(
@RequestHeader("Authorization") String accessToken) {
Expand All @@ -45,7 +45,7 @@ public ResponseEntity<ApiResponse<String>> logout(
.body(ApiResponse.success("로그아웃 되었습니다."));
}

@PostMapping("/reissue")
@PostMapping("/api/v1/auth/reissue")
@Operation(summary = "AccessToken 재발급", description = "AccessToken을 재발급합니다.")
public ResponseEntity<ApiResponse<?>> reissue(
@RequestHeader("Authorization") String accessToken,
Expand All @@ -62,7 +62,7 @@ public ResponseEntity<ApiResponse<?>> reissue(
.body(ApiResponse.success(jwtTokenResponse));
}

@PostMapping("/auth/token")
@PostMapping("/api/v1/auth/token")
@Operation(summary = "로그인 결과 받기", description = "로그인 성공 리다이렉트로 받은 일회용 code를 교환해 "
+ "accessToken(\"Bearer \" 접두어 포함), memberId, uuid, firstLogin을 받습니다. "
+ "code는 60초 동안 한 번만 쓸 수 있고, 잘못되었거나 만료되었거나 이미 쓴 code면 401입니다.")
Expand All @@ -72,7 +72,7 @@ public ResponseEntity<ApiResponse<LoginResult>> exchangeLoginCode(@Valid @Reques
return ResponseEntity.ok(ApiResponse.success(result));
}

@DeleteMapping("/withdraw")
@DeleteMapping("/api/v1/auth/withdraw")
@Operation(summary = "회원탈퇴", description = "회원 정보를 삭제하고 로그아웃 처리합니다.")
public ResponseEntity<ApiResponse<String>> withdraw(
@RequestHeader("Authorization") String accessToken) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ public TestAccountLoginController(JwtTokenProvider jwtTokenProvider, MemberRepos
this.testLoginKey = StringUtils.hasText(testLoginKey) ? testLoginKey.getBytes(StandardCharsets.UTF_8) : null;
}

@PostMapping("/auth/test-login")
@PostMapping("/api/v1/auth/test-login")
public ResponseEntity<ApiResponse<?>> login(
@RequestHeader(value = KEY_HEADER, required = false) String key,
@RequestBody(required = false) TestLoginRequest request) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ public class TestLoginController {
private final JwtTokenProvider jwtTokenProvider;
private final TestAccountProperties testAccountProperties;

@PostMapping("/dev/test-login")
@PostMapping("/api/v1/dev/test-login")
@Operation(summary = "[개발용] 테스트 계정 로그인",
description = "[dev/local 환경만] 설정된 테스트 계정으로 바로 로그인하여 JWT 토큰을 발급받습니다.")
public ResponseEntity<ApiResponse<JwtTokenResponse>> testLogin(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@

/**
* 로그인 성공 결과를 일회용 code로 잠시 보관한다. 리다이렉트 URL에는 code만 싣고,
* 프론트가 POST /auth/token으로 code를 한 번 교환해 결과를 받는다.
* 프론트가 POST /api/v1/auth/token으로 code를 한 번 교환해 결과를 받는다.
*/
@Slf4j
@Component
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@
public class AuthorizationFilter extends OncePerRequestFilter {

// 재발급은 만료된 액세스 토큰으로 요청하므로 필터에서 검증하지 않고 서비스에서 서명만 확인한다
private static final String REISSUE_PATH = "/reissue";
private static final String REISSUE_PATH = "/api/v1/auth/reissue";

private final JwtTokenProvider jwtTokenProvider;

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -125,7 +125,7 @@ public void oauthSuccessHandler(HttpServletRequest request,
// 콜백에서 꺼낸 인가 요청의 redirect_uri가 허용 출처일 때만 쓰고, 아니면 기본 콜백 주소로 보낸다
String redirectUri = redirectUriPolicy.resolveFromCallback(request);

// 토큰은 URL에 싣지 않고, 프론트가 POST /auth/token으로 교환할 일회용 code만 붙인다
// 토큰은 URL에 싣지 않고, 프론트가 POST /api/v1/auth/token으로 교환할 일회용 code만 붙인다
String code = loginCodeStore.issue(
new LoginResult(accessToken, member.getId(), member.getUuid(), member.isFirstLogin()));
response.sendRedirect(redirectUri + (redirectUri.contains("?") ? "&" : "?") + "code=" + code);
Expand Down
4 changes: 2 additions & 2 deletions src/main/java/backend/globber/config/SwaggerConfig.java
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,8 @@
import org.springframework.context.annotation.Configuration;

@Configuration
@OpenAPIDefinition(servers = {@Server(url = "https://globber.world/api", description = "운영 서버"),
@Server(url = "https://dev.globber.world/api", description = "개발 서버"),
@OpenAPIDefinition(servers = {@Server(url = "https://globber.world", description = "운영 서버"),
@Server(url = "https://dev.globber.world", description = "개발 서버"),
@Server(url = "http://localhost:8080", description = "로컬 서버")})
public class SwaggerConfig {

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("api/v1/globes")
@RequestMapping("/api/v1/globes")
@Tag(name = "지구본 API", description = "사용자의 여행 기록 지구본 조회 API")
public class GlobeController {

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,12 +26,12 @@ class CustomOAuth2AuthorizationRequestResolverTest {
.userInfoUri("https://kapi.kakao.com/v2/user/me")
.userNameAttributeName("id")
.build()),
"/oauth2/authorization",
"/api/v1/oauth2/authorization",
new RedirectUriPolicy(List.of("https://globber.world"), "https://globber.world/login/oauth/success"));

private MockHttpServletRequest loginStart(String redirectUri) {
MockHttpServletRequest request = new MockHttpServletRequest("GET", "/oauth2/authorization/kakao");
request.setServletPath("/oauth2/authorization/kakao");
MockHttpServletRequest request = new MockHttpServletRequest("GET", "/api/v1/oauth2/authorization/kakao");
request.setServletPath("/api/v1/oauth2/authorization/kakao");
request.setParameter("redirect_uri", redirectUri);
return request;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -232,7 +232,7 @@ void validBearer_ok() {
RestAssured.given().log().all()
.header("Authorization", validBearerToken())
.when()
.post("/logout")
.post("/api/v1/auth/logout")
.then().log().all()
.statusCode(200);
}
Expand All @@ -247,7 +247,7 @@ void rawValidToken_unauthorized() {
RestAssured.given().log().all()
.header("Authorization", validBearerToken().substring(BEARER.length()))
.when()
.post("/logout")
.post("/api/v1/auth/logout")
.then().log().all()
.statusCode(401)
.body("status", equalTo("fail"));
Expand Down Expand Up @@ -275,7 +275,7 @@ void expiredBearerAccessToken_reissued() {
.header("Authorization", BEARER + expiredRawJwt())
.cookie("RefreshToken", refreshToken)
.when()
.post("/reissue")
.post("/api/v1/auth/reissue")
.then().log().all()
.statusCode(200)
.body("data.accessToken", notNullValue());
Expand All @@ -292,7 +292,7 @@ void rawExpiredAccessToken_unauthorized() {
.header("Authorization", expiredRawJwt())
.cookie("RefreshToken", refreshToken)
.when()
.post("/reissue")
.post("/api/v1/auth/reissue")
.then().log().all()
.statusCode(401)
.body("status", equalTo("fail"));
Expand All @@ -309,7 +309,7 @@ void unsignedExpiredAccessToken_unauthorized() {
.header("Authorization", BEARER + unsignedExpiredRawJwt())
.cookie("RefreshToken", refreshToken)
.when()
.post("/reissue")
.post("/api/v1/auth/reissue")
.then().log().all()
.statusCode(401)
.body("status", equalTo("fail"));
Expand All @@ -328,7 +328,7 @@ void differentRefreshToken_unauthorized() {
.header("Authorization", BEARER + expiredRawJwt())
.cookie("RefreshToken", differentRefreshToken)
.when()
.post("/reissue")
.post("/api/v1/auth/reissue")
.then().log().all()
.statusCode(401)
.body("status", equalTo("fail"))
Expand All @@ -346,7 +346,7 @@ void forgedAccessToken_unauthorized() {
.header("Authorization", BEARER + forgedRawJwt())
.cookie("RefreshToken", refreshToken)
.when()
.post("/reissue")
.post("/api/v1/auth/reissue")
.then().log().all()
.statusCode(401)
.body("status", equalTo("fail"));
Expand Down
91 changes: 91 additions & 0 deletions src/test/java/backend/globber/auth/controller/ApiV1PathsTest.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,91 @@
package backend.globber.auth.controller;

import static org.hamcrest.Matchers.anyOf;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.everyItem;
import static org.hamcrest.Matchers.not;
import static org.hamcrest.Matchers.startsWith;

import backend.globber.city.service.RedisWarmUp;
import backend.globber.support.PostgresTestConfig;
import backend.globber.support.RedisTestConfig;
import io.restassured.RestAssured;
import io.restassured.http.ContentType;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.web.server.LocalServerPort;
import org.springframework.context.annotation.Import;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.bean.override.mockito.MockitoBean;

/**
* GLB-298: 모든 API를 /api/v1 아래로 모은다. 예전 경로는 더 이상 동작하지 않는다.
* 카카오 콜백(/login/oauth2/code/*), actuator, Swagger는 그대로 둔다.
*/
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@ContextConfiguration(initializers = RedisTestConfig.Initializer.class)
@Import({PostgresTestConfig.class, RedisTestConfig.class})
class ApiV1PathsTest {

@MockitoBean
private RedisWarmUp redisWarmUp;

@LocalServerPort
private int port;

@BeforeEach
void setUp() {
RestAssured.port = port;
}

@Test
@DisplayName("인증 관련 API는 /api/v1/auth 아래에서 동작하고 예전 경로는 없다")
void authEndpoints_movedUnderApiV1() {
// when & then: 새 경로는 컨트롤러까지 도달한다(인증·코드가 없어서 401)
RestAssured.given().contentType(ContentType.JSON).body("{\"code\":\"unknown\"}")
.when().post("/api/v1/auth/token").then().statusCode(401);
RestAssured.given().when().post("/api/v1/auth/reissue").then().statusCode(not(anyOf(is(404), is(405))));
RestAssured.given().when().post("/api/v1/auth/logout").then().statusCode(401);
RestAssured.given().when().delete("/api/v1/auth/withdraw").then().statusCode(401);

// 예전 경로는 없다
RestAssured.given().contentType(ContentType.JSON).body("{\"code\":\"unknown\"}")
.when().post("/auth/token").then().statusCode(anyOf(is(404), is(405)));
RestAssured.given().when().post("/reissue").then().statusCode(anyOf(is(404), is(405)));
RestAssured.given().when().post("/logout").then().statusCode(anyOf(is(404), is(405)));
RestAssured.given().when().delete("/withdraw").then().statusCode(anyOf(is(404), is(405)));
}

@Test
@DisplayName("개발용 테스트 로그인은 /api/v1/dev/test-login에서 동작한다")
void devTestLogin_movedUnderApiV1() {
// when & then
RestAssured.given().queryParam("email", "not-a-test-account@example.com")
.when().post("/api/v1/dev/test-login").then().statusCode(not(anyOf(is(404), is(405))));
RestAssured.given().queryParam("email", "not-a-test-account@example.com")
.when().post("/dev/test-login").then().statusCode(anyOf(is(404), is(405)));
}

@Test
@DisplayName("카카오 로그인 시작은 /api/v1/oauth2/authorization/kakao이고 예전 경로는 없다")
void oauthAuthorization_movedUnderApiV1() {
// when & then
RestAssured.given().redirects().follow(false)
.when().get("/api/v1/oauth2/authorization/kakao")
.then().statusCode(302).header("Location", containsString("kauth.kakao.com"));
RestAssured.given().redirects().follow(false)
.when().get("/oauth2/authorization/kakao")
.then().statusCode(404);
}

@Test
@DisplayName("API 문서에 나오는 모든 경로는 /api/v1로 시작한다")
void documentedPaths_allUnderApiV1() {
// when & then
RestAssured.given().when().get("/v3/api-docs/GLOBBER API").then().statusCode(200)
.body("paths.keySet()", everyItem(startsWith("/api/v1/")));
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -82,7 +82,7 @@ void exchange_onceOnly() {
// when & then
RestAssured.given().log().all()
.contentType(ContentType.JSON).body(body(code))
.when().post("/auth/token")
.when().post("/api/v1/auth/token")
.then().log().all()
.statusCode(200)
.body("status", equalTo("success"))
Expand All @@ -92,7 +92,7 @@ void exchange_onceOnly() {
.body("data.firstLogin", equalTo(true));

RestAssured.given().contentType(ContentType.JSON).body(body(code))
.when().post("/auth/token")
.when().post("/api/v1/auth/token")
.then().statusCode(401).body("status", equalTo("fail"));
}

Expand All @@ -101,10 +101,10 @@ void exchange_onceOnly() {
void exchange_invalid() {
// when & then
RestAssured.given().contentType(ContentType.JSON).body(body("unknown-code"))
.when().post("/auth/token")
.when().post("/api/v1/auth/token")
.then().statusCode(401).body("status", equalTo("fail"));
RestAssured.given().contentType(ContentType.JSON).body("{}")
.when().post("/auth/token")
.when().post("/api/v1/auth/token")
.then().statusCode(400).body("status", equalTo("fail"));
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,7 @@ private void logoutOk() {
RestAssured.given().log().all()
.header("Authorization", token)
.when()
.post("/logout")
.post("/api/v1/auth/logout")
.then().log().all()
.statusCode(200);
}
Expand Down Expand Up @@ -114,7 +114,7 @@ void logout_withoutRefreshToken_ok() {
RestAssured.given().log().all()
.header("Authorization", token)
.when()
.post("/logout")
.post("/api/v1/auth/logout")
.then().log().all()
.statusCode(200)
.header("Set-Cookie", containsString("RefreshToken="))
Expand All @@ -132,7 +132,7 @@ void afterWithdraw_tokenBlacklisted() {
RestAssured.given().log().all()
.header("Authorization", token)
.when()
.delete("/withdraw")
.delete("/api/v1/auth/withdraw")
.then().log().all()
.statusCode(200);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -59,15 +59,15 @@ void keyNotConfigured_notFound() {
for (String key : new String[]{"", "anything"}) {
RestAssured.given().contentType(ContentType.JSON).header("X-Test-Login-Key", key)
.body("{\"email\": \"" + TEST_EMAIL + "\"}")
.when().post("/auth/test-login")
.when().post("/api/v1/auth/test-login")
.then().statusCode(404).body("status", equalTo("fail"))
.body("data", equalTo("요청한 경로를 찾을 수 없습니다."));
}
// 본문이 비거나 없어도 400이 아니라 404다(API 존재를 드러내지 않는다)
RestAssured.given().contentType(ContentType.JSON).body("{}")
.when().post("/auth/test-login").then().statusCode(404);
.when().post("/api/v1/auth/test-login").then().statusCode(404);
RestAssured.given().contentType(ContentType.JSON)
.when().post("/auth/test-login").then().statusCode(404);
.when().post("/api/v1/auth/test-login").then().statusCode(404);
}

@Test
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,7 @@ private ExtractableResponse<Response> login(String key, String email) {
if (key != null) {
request.header("X-Test-Login-Key", key);
}
return request.when().post("/auth/test-login").then().extract();
return request.when().post("/api/v1/auth/test-login").then().extract();
}

@Test
Expand Down Expand Up @@ -127,7 +127,7 @@ void realUser_forbidden() {
@DisplayName("email이 비어 있으면 400이다")
void blankEmail_badRequest() {
RestAssured.given().contentType(ContentType.JSON).header("X-Test-Login-Key", KEY).body("{}")
.when().post("/auth/test-login")
.when().post("/api/v1/auth/test-login")
.then().statusCode(400).body("status", equalTo("fail"));
}

Expand All @@ -136,6 +136,6 @@ void blankEmail_badRequest() {
void hiddenFromApiDocs() {
String docs = RestAssured.given().when().get("/v3/api-docs/GLOBBER API")
.then().statusCode(200).extract().asString();
assertThat(docs).doesNotContain("/auth/test-login");
assertThat(docs).doesNotContain("/api/v1/auth/test-login");
}
}
4 changes: 2 additions & 2 deletions src/test/java/backend/globber/config/SwaggerConfigTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -49,8 +49,8 @@ void apiDocs_servers(String apiDocsPath) {
response.statusCode(200)
.body("servers", hasSize(3))
.body("servers.url", contains(
"https://globber.world/api",
"https://dev.globber.world/api",
"https://globber.world",
"https://dev.globber.world",
"http://localhost:8080"))
.body("servers.description", contains("운영 서버", "개발 서버", "로컬 서버"))
.body("servers.url", not(hasItem("/")))
Expand Down
Loading
Loading