-
Notifications
You must be signed in to change notification settings - Fork 0
[ZIM-35] OAuth 콜백 리다이렉트 및 리뷰 피드백 반영 #19
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from 3 commits
Commits
Show all changes
8 commits
Select commit
Hold shift + click to select a range
ff76947
feat: OAuth 콜백 URL 기반 로그인 성공/실패 리다이렉트 처리
buddle031 c29b46b
refactor: 마이페이지 DTO 경계를 애플리케이션/엔트리포인트로 분리
buddle031 acc13f2
refactor: review feedback 반영 (displayName 한글화, repository 네이밍 정리, rol…
buddle031 963a042
refactor: #17 응답 규약 반영 및 persistence 엔티티 네이밍 정리
buddle031 cb82a71
fix: #17 응답 규약(of) 반영으로 CI 컴파일 오류 해결
buddle031 bd9531c
Merge remote-tracking branch 'origin/main' into chore/local-env-guide…
mike7643 05cd650
refactor: user 도메인/영속 모델 네이밍 충돌 해소
mike7643 9d3b0fa
refactor: user 영속 모델 네이밍 정리 및 예외 규약 반영
buddle031 File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
158 changes: 158 additions & 0 deletions
158
src/main/java/com/zimdugo/auth/application/OAuth2CallbackUrlCookieManager.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,158 @@ | ||
| package com.zimdugo.auth.application; | ||
|
|
||
| import jakarta.annotation.PostConstruct; | ||
| import jakarta.servlet.http.Cookie; | ||
| import jakarta.servlet.http.HttpServletRequest; | ||
| import jakarta.servlet.http.HttpServletResponse; | ||
| import java.net.URI; | ||
| import java.net.URISyntaxException; | ||
| import java.net.URLDecoder; | ||
| import java.net.URLEncoder; | ||
| import java.nio.charset.StandardCharsets; | ||
| import java.util.Arrays; | ||
| import java.util.LinkedHashSet; | ||
| import java.util.Set; | ||
| import lombok.extern.slf4j.Slf4j; | ||
| import org.springframework.beans.factory.annotation.Value; | ||
| import org.springframework.http.HttpHeaders; | ||
| import org.springframework.http.ResponseCookie; | ||
| import org.springframework.stereotype.Component; | ||
|
|
||
| @Slf4j | ||
| @Component | ||
| public class OAuth2CallbackUrlCookieManager { | ||
|
|
||
| private static final String CALLBACK_URL_PARAM = "callbackUrl"; | ||
| private static final String CALLBACK_URL_COOKIE_NAME = "oauth2_callback_url"; | ||
| private static final int CALLBACK_URL_COOKIE_MAX_AGE_SECONDS = 300; | ||
| private static final String SAME_SITE_POLICY = "Lax"; | ||
| private static final String RELATIVE_PATH_DEFAULT = "/"; | ||
|
|
||
| @Value("${auth.callback.frontend-base-url:http://localhost:3000}") | ||
| private String frontendBaseUrl; | ||
|
|
||
| @Value("${auth.callback.allowed-origins:http://localhost:3000,http://localhost:5173}") | ||
| private String allowedOriginsProperty; | ||
|
|
||
| private Set<String> allowedOrigins; | ||
|
|
||
| @PostConstruct | ||
| void initializeAllowedOrigins() { | ||
| this.allowedOrigins = new LinkedHashSet<>(); | ||
| Arrays.stream(allowedOriginsProperty.split(",")) | ||
| .map(String::trim) | ||
| .filter(v -> !v.isBlank()) | ||
| .map(this::extractOrigin) | ||
| .forEach(allowedOrigins::add); | ||
|
|
||
| String frontendOrigin = extractOrigin(frontendBaseUrl); | ||
| if (frontendOrigin != null) { | ||
| allowedOrigins.add(frontendOrigin); | ||
| } | ||
| } | ||
|
|
||
| public void saveCallbackUrl(HttpServletRequest request, HttpServletResponse response) { | ||
| String callbackUrl = normalize(request.getParameter(CALLBACK_URL_PARAM)); | ||
| addCookie(response, callbackUrl, CALLBACK_URL_COOKIE_MAX_AGE_SECONDS); | ||
| } | ||
|
|
||
| public String resolveCallbackUrl(HttpServletRequest request) { | ||
| Cookie[] cookies = request.getCookies(); | ||
| if (cookies == null) { | ||
| return toFrontendUrl(RELATIVE_PATH_DEFAULT); | ||
| } | ||
|
|
||
| for (Cookie cookie : cookies) { | ||
| if (CALLBACK_URL_COOKIE_NAME.equals(cookie.getName())) { | ||
| return normalize(decode(cookie.getValue())); | ||
| } | ||
| } | ||
|
|
||
| return toFrontendUrl(RELATIVE_PATH_DEFAULT); | ||
| } | ||
|
|
||
| public void clearCallbackUrl(HttpServletResponse response) { | ||
| addCookie(response, "", 0); | ||
| } | ||
|
|
||
| private void addCookie(HttpServletResponse response, String value, int maxAgeSeconds) { | ||
| ResponseCookie cookie = ResponseCookie.from(CALLBACK_URL_COOKIE_NAME, encode(value)) | ||
| .httpOnly(true) | ||
| .secure(false) | ||
| .path("/") | ||
| .maxAge(maxAgeSeconds) | ||
| .sameSite(SAME_SITE_POLICY) | ||
| .build(); | ||
|
|
||
| response.addHeader(HttpHeaders.SET_COOKIE, cookie.toString()); | ||
| } | ||
|
|
||
| private String normalize(String callbackUrl) { | ||
| if (callbackUrl == null || callbackUrl.isBlank()) { | ||
| return toFrontendUrl(RELATIVE_PATH_DEFAULT); | ||
| } | ||
|
|
||
| String trimmed = callbackUrl.trim(); | ||
| if (trimmed.contains("\r") || trimmed.contains("\n")) { | ||
| log.warn("Unsafe callbackUrl detected. fallback to default. callbackUrl={}", trimmed); | ||
| return toFrontendUrl(RELATIVE_PATH_DEFAULT); | ||
| } | ||
|
|
||
| if (trimmed.startsWith("/") && !trimmed.startsWith("//")) { | ||
| return toFrontendUrl(trimmed); | ||
| } | ||
|
|
||
| String origin = extractOrigin(trimmed); | ||
| if (origin == null || !allowedOrigins.contains(origin)) { | ||
| log.warn("Unsafe callbackUrl detected. fallback to default. callbackUrl={}", trimmed); | ||
| return toFrontendUrl(RELATIVE_PATH_DEFAULT); | ||
| } | ||
|
|
||
| return trimmed; | ||
| } | ||
|
|
||
| private String encode(String value) { | ||
| return URLEncoder.encode(value, StandardCharsets.UTF_8); | ||
| } | ||
|
|
||
| private String decode(String value) { | ||
| try { | ||
| return URLDecoder.decode(value, StandardCharsets.UTF_8); | ||
| } catch (IllegalArgumentException e) { | ||
| log.warn("Failed to decode callback cookie. fallback to default.", e); | ||
| return toFrontendUrl(RELATIVE_PATH_DEFAULT); | ||
| } | ||
| } | ||
|
|
||
| private String toFrontendUrl(String path) { | ||
| String base = frontendBaseUrl; | ||
| if (frontendBaseUrl.endsWith("/")) { | ||
| base = frontendBaseUrl.substring(0, frontendBaseUrl.length() - 1); | ||
| } | ||
| if (path == null || path.isBlank() || "/".equals(path)) { | ||
| return base + "/"; | ||
| } | ||
| return base + path; | ||
| } | ||
|
|
||
| private String extractOrigin(String url) { | ||
| try { | ||
| URI uri = new URI(url); | ||
| if (uri.getScheme() == null || uri.getHost() == null) { | ||
| return null; | ||
| } | ||
|
|
||
| String scheme = uri.getScheme().toLowerCase(); | ||
| if (!"http".equals(scheme) && !"https".equals(scheme)) { | ||
| return null; | ||
| } | ||
|
|
||
| if (uri.getPort() == -1) { | ||
| return scheme + "://" + uri.getHost().toLowerCase(); | ||
| } | ||
| return scheme + "://" + uri.getHost().toLowerCase() + ":" + uri.getPort(); | ||
| } catch (URISyntaxException e) { | ||
| return null; | ||
| } | ||
| } | ||
| } |
40 changes: 40 additions & 0 deletions
40
src/main/java/com/zimdugo/auth/application/OAuth2FailureHandler.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,40 @@ | ||
| package com.zimdugo.auth.application; | ||
|
|
||
| import jakarta.servlet.http.HttpServletRequest; | ||
| import jakarta.servlet.http.HttpServletResponse; | ||
| import java.io.IOException; | ||
| import lombok.RequiredArgsConstructor; | ||
| import lombok.extern.slf4j.Slf4j; | ||
| import org.springframework.security.core.AuthenticationException; | ||
| import org.springframework.security.web.authentication.AuthenticationFailureHandler; | ||
| import org.springframework.stereotype.Component; | ||
| import org.springframework.web.util.UriComponentsBuilder; | ||
|
|
||
| @Slf4j | ||
| @Component | ||
| @RequiredArgsConstructor | ||
| public class OAuth2FailureHandler implements AuthenticationFailureHandler { | ||
|
|
||
| private final OAuth2CallbackUrlCookieManager callbackUrlCookieManager; | ||
|
|
||
| @Override | ||
| public void onAuthenticationFailure( | ||
| HttpServletRequest request, | ||
| HttpServletResponse response, | ||
| AuthenticationException exception | ||
| ) throws IOException { | ||
| String callbackUrl = callbackUrlCookieManager.resolveCallbackUrl(request); | ||
| callbackUrlCookieManager.clearCallbackUrl(response); | ||
|
|
||
| log.warn("oauth login failure. callbackUrl={}, reason={}", callbackUrl, exception.getMessage()); | ||
| response.sendRedirect(appendCode(callbackUrl, "LOGIN_FAILED")); | ||
| } | ||
|
|
||
| private String appendCode(String callbackUrl, String code) { | ||
| return UriComponentsBuilder.fromUriString(callbackUrl) | ||
| .replaceQueryParam("code", code) | ||
| .build(true) | ||
| .toUriString(); | ||
| } | ||
| } | ||
|
|
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
35 changes: 35 additions & 0 deletions
35
src/main/java/com/zimdugo/auth/entrypoint/OAuth2CallbackUrlCaptureFilter.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,35 @@ | ||
| package com.zimdugo.auth.entrypoint; | ||
|
|
||
| import com.zimdugo.auth.application.OAuth2CallbackUrlCookieManager; | ||
| import jakarta.servlet.FilterChain; | ||
| import jakarta.servlet.ServletException; | ||
| import jakarta.servlet.http.HttpServletRequest; | ||
| import jakarta.servlet.http.HttpServletResponse; | ||
| import java.io.IOException; | ||
| import lombok.RequiredArgsConstructor; | ||
| import org.springframework.stereotype.Component; | ||
| import org.springframework.web.filter.OncePerRequestFilter; | ||
|
|
||
| @Component | ||
| @RequiredArgsConstructor | ||
| public class OAuth2CallbackUrlCaptureFilter extends OncePerRequestFilter { | ||
|
|
||
| private static final String OAUTH2_AUTHORIZATION_REQUEST_PREFIX = "/oauth2/authorization/"; | ||
|
|
||
| private final OAuth2CallbackUrlCookieManager callbackUrlCookieManager; | ||
|
|
||
| @Override | ||
| protected void doFilterInternal( | ||
| HttpServletRequest request, | ||
| HttpServletResponse response, | ||
| FilterChain filterChain | ||
| ) throws ServletException, IOException { | ||
| callbackUrlCookieManager.saveCallbackUrl(request, response); | ||
| filterChain.doFilter(request, response); | ||
| } | ||
|
|
||
| @Override | ||
| protected boolean shouldNotFilter(HttpServletRequest request) { | ||
| return !request.getRequestURI().startsWith(OAUTH2_AUTHORIZATION_REQUEST_PREFIX); | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.