FastAPI에서 OAuth2 + 소셜 로그인 연동하기 (Google OAuth2 예제)
OAuth2 소셜 로그인 개념 정리
OAuth2는 외부 서비스를 통해 로그인과 인증을 위임하는 프로토콜입니다.
Google, Kakao, Naver 같은 플랫폼을 통해 로그인 기능을 제공받는 것이 대표적인 예입니다.
OAuth2 인증 흐름 요약
- 클라이언트가 소셜 로그인 버튼 클릭
- 소셜 플랫폼의 인증 서버로 리디렉션
- 사용자가 로그인 및 권한 승인
- 서버가 인증 코드를 받아 access_token 획득
- access_token으로 사용자 정보 조회
FastAPI에서 OAuth2를 쓰는 이유
- 별도 회원가입 없이 로그인 구현 가능
- 보안성 높고, 사용자 인증/프로필 관리 용이
- 다양한 플랫폼과 손쉬운 연동 (Google, GitHub, Kakao 등)
FastAPI에서 Google OAuth2 로그인 구현
1. 필수 패키지 설치
pip install fastapi[all] python-dotenv httpx authlib
authlib
는 OAuth 클라이언트를 지원하는 라이브러리입니다. httpx
는 HTTP 요청 처리용입니다.
2. Google OAuth2 클라이언트 등록
- https://console.cloud.google.com → 프로젝트 생성
- API 및 서비스 → 사용자 인증 정보 → OAuth 2.0 클라이언트 ID 생성
- 리디렉션 URI:
http://localhost:8000/auth/callback
- 클라이언트 ID와 Secret을 .env 파일에 저장
3. .env 파일 예시
GOOGLE_CLIENT_ID=your_google_client_id
GOOGLE_CLIENT_SECRET=your_google_client_secret
4. FastAPI OAuth2 구현 코드 (main.py)
import os
from fastapi import FastAPI, Request
from fastapi.responses import RedirectResponse, HTMLResponse
from authlib.integrations.starlette_client import OAuth
from starlette.config import Config
from dotenv import load_dotenv
load_dotenv()
app = FastAPI()
# OAuth 설정
config = Config(environ=os.environ)
oauth = OAuth(config)
oauth.register(
name='google',
client_id=os.environ["GOOGLE_CLIENT_ID"],
client_secret=os.environ["GOOGLE_CLIENT_SECRET"],
server_metadata_url='https://accounts.google.com/.well-known/openid-configuration',
client_kwargs={
'scope': 'openid email profile'
}
)
@app.get("/")
def home():
return HTMLResponse('구글 로그인')
@app.get("/auth/login")
async def login(request: Request):
redirect_uri = request.url_for('auth_callback')
return await oauth.google.authorize_redirect(request, redirect_uri)
@app.get("/auth/callback")
async def auth_callback(request: Request):
token = await oauth.google.authorize_access_token(request)
user_info = await oauth.google.parse_id_token(request, token)
return {
"access_token": token['access_token'],
"user_info": user_info
}
5. 실행 및 테스트
uvicorn main:app --reload
http://localhost:8000
접속 → “구글 로그인” 클릭- Google 로그인 창 → 로그인 후 리디렉션됨
- 응답 JSON으로 access_token + 유저 정보 확인 가능
이 방식은 access_token + profile을 얻은 뒤, DB 연동하여 회원가입 또는 로그인 처리를 이어서 구현할 수 있습니다.
로그인 데이터 연동을 위한 기타 방안
1. 유저 DB 연동
user = db.get_by_email(user_info["email"])
if not user:
user = db.create_user(user_info)
이메일이 처음인 경우 회원가입, 이미 있으면 로그인 처리 등 소셜 계정 연동 로직을 자유롭게 구성할 수 있습니다.
2. 로그인 세션 관리 방식 선택
- JWT 기반: 토큰을 프론트에 반환해 이후 요청에서 사용
- 세션 기반:
set_cookie()
로 세션 쿠키 전달
3. 리디렉션 URI 고정 및 검증
'redirect_uri': 'http://localhost:8000/auth/callback'
Google OAuth2 설정에서 반드시 리디렉션 URI가 일치해야 하며, HTTPS 환경에서는 https:// 사용 권장됩니다.
4. 기타 소셜 로그인 확장 (GitHub, Kakao 등)
authlib.register()
의 설정만 바꾸면 Kakao, GitHub 등 다양한 소셜 서비스와 연동할 수 있습니다.
서버 메타데이터 URL과 scope만 해당 플랫폼에 맞게 조정하면 됩니다. FastAPI + OAuth2는 소셜 로그인 구현을 매우 간단하고 강력하게 만들어줍니다. 별도의 비밀번호 저장 없이도, Google 등 외부 인증에 의존해 보안성과 사용자 경험을 동시에 챙길 수 있습니다.