Project/Boilerplate

AWS EC2에서 OAuth2.0 로그인 및 쿠키 저장 문제

조용우 2025. 4. 21. 18:59

문제:

OAuth2.0 로그인을 시도하면,

401 Unauthorized를 응답함.

Request URL:
http://<ec2-IP>:8080/login/oauth2/code/google?state=<code>&scope=email+profile+https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fuserinfo.profile+openid+https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fuserinfo.email&authuser=0&prompt=none
Request Method:
GET
Status Code:
401 Unauthorized
Remote Address:
<ec2-IP>:8080
Referrer Policy:
strict-origin-when-cross-origin

 

SecurityConfig.java

OAuth2.0 로그인 부분에 실패 핸들러 로그 추가

.failureHandler((request, response, exception) -> {
    log.error("OAuth 실패! 이유: {}", exception.getMessage()); // 간단 요약
    response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "OAuth 로그인 실패: " + exception.getMessage());
})

 

2025-04-15 10:51:53.186 [http-nio-0.0.0.0-8080-exec-5] ERROR c.b.b.global.config.SecurityConfig - ❌ OAuth2 로그인 실패!
org.springframework.security.oauth2.core.OAuth2AuthenticationException: [authorization_request_not_found]

진짜 원인: 세션 쿠키가 유지되지 않음

Spring은 OAuth2AuthorizationRequestRedirectFilter 단계에서 인증 요청 정보를 HttpSession에 저장합니다.
그런데, EC2 환경에서는 다음 중 하나 이상의 이유로 브라우저가 쿠키를 보내지 않습니다:


🔍 세션 쿠키 누락의 주요 원인

원인 설명 해결 방법
SameSite=Lax 기본 정책 OAuth2 리디렉션은 cross-site로 인식됨 → 쿠키 미포함 SameSite=None; Secure 필요
HTTPS 아닌 HTTP 사용 SameSite=None은 Secure 필수인데 HTTPS가 아님 → 쿠키 차단됨 🔥 HTTPS 설정 필요
리디렉션 도중 도메인이 변경됨 프론트 → Google → 백엔드 도중 도메인 mismatch Host 고정 & HTTPS

 

따라서, https 설정 후 쿠키 설정 시

cookie.setSecure(true);
cookie.setAttribute("SameSite", "None");

추가해주면 해결 될 것. 혹은, public DNS 설정 하여 SameSite 설정은 Lax 유지.