Java
Spring WebClient기반 Google OAuth2 인증
마시멜로를찾아서
2025. 6. 16. 13:01
728x90
반응형
Spring WebClient를 사용하여 Google API (예: Google Calendar API, Gmail API, Drive API 등)**에 OAuth2 인증을 붙여 안정적으로 호출하는 전체 예제
✅ 시나리오: Google Calendar API 호출 (https://www.googleapis.com/calendar/v3/users/me/calendarList)
📌 사전 준비 (Google Cloud Console)
- https://console.cloud.google.com/ 접속
- 새 프로젝트 생성 후 "OAuth 동의 화면" 설정
- OAuth 2.0 클라이언트 ID/Secret 발급 (사용자 인증 방식: Authorization Code Flow or Client Credentials)
- Redirect URI: 예) http://localhost:8080/login/oauth2/code/google
✅ 1. 의존성 추가
implementation 'org.springframework.boot:spring-boot-starter-oauth2-client'
implementation 'org.springframework.boot:spring-boot-starter-webflux'
✅ 2. application.yml 설정 (Spring OAuth2 Client)
spring:
security:
oauth2:
client:
registration:
google:
client-id: <your-client-id>
client-secret: <your-client-secret>
scope: https://www.googleapis.com/auth/calendar.readonly
redirect-uri: "{baseUrl}/login/oauth2/code/{registrationId}"
authorization-grant-type: authorization_code
client-name: Google
provider:
google:
authorization-uri: https://accounts.google.com/o/oauth2/v2/auth
token-uri: https://oauth2.googleapis.com/token
user-info-uri: https://www.googleapis.com/oauth2/v3/userinfo
✅ 3. WebClient 구성 (OAuth2 인증 자동 적용)
@Configuration
public class WebClientConfig {
@Bean
public WebClient googleWebClient(ReactiveOAuth2AuthorizedClientManager manager) {
ServerOAuth2AuthorizedClientExchangeFilterFunction oauth =
new ServerOAuth2AuthorizedClientExchangeFilterFunction(manager);
oauth.setDefaultClientRegistrationId("google");
return WebClient.builder()
.apply(oauth.oauth2Configuration())
.build();
}
}
✅ 4. 서비스에서 Google API 호출
@Service
@RequiredArgsConstructor
public class GoogleCalendarService {
private final WebClient googleWebClient;
public Mono<String> getCalendarList() {
return googleWebClient
.get()
.uri("https://www.googleapis.com/calendar/v3/users/me/calendarList")
.retrieve()
.bodyToMono(String.class);
}
}
✅ 5. 로그인 후 사용 가능 (OAuth2 Flow 기반)
Spring Boot Security를 사용하고 있으므로 /login/oauth2/code/google 리다이렉트 이후 사용자 인증이 완료되면
WebClient는 자동으로 access token을 붙여 Google API를 호출합니다.
즉, 사용자가 먼저 /oauth2/authorization/google 경로로 진입해 Google OAuth 로그인 후,
WebClient를 통해 API 호출이 가능합니다.
💡 실무 팁
항목팁
사용자 인증 O | authorization_code 방식 (me endpoint 사용 가능) |
사용자 인증 없이 호출 | service account 또는 client_credentials 방식 필요 (Google API에 따라 미지원) |
scope | API별로 scope가 다르므로 반드시 확인 (calendar, drive, gmail, etc.) |
토큰 만료 | Spring Security가 자동 갱신 (authorization_code 기반) |
📦 주요 Google API + Scope 예시
📌 참고
- 서비스 계정으로 접근하려면 GoogleCredential을 사용하거나 GCP 라이브러리 사용 권장
- 사용자 계정 접근 시엔 반드시 OAuth2 인증 → 토큰 저장/관리 필요
✅ 결론
WebClient + OAuth2 + Google API 조합은 Spring Security와 함께 매우 안정적으로 구현 가능하며,
인증 후에는 토큰 자동 관리까지 포함되어 실무에서도 매우 자주 사용됩니다.
728x90
반응형