구글 OAuth를 통한 Reddit 클론 인증 구현 방법
카테고리
프로그래밍/소프트웨어 개발
서브카테고리
디자인 툴
대상자
- 대상자: React + Django 기반의 풀스택 애플리케이션 개발자
- 난이도: 중급 (인증 흐름 이해, Google Cloud 설정, Django 서버 구현 기초 지식 필요)
핵심 요약
- 구글 OAuth 흐름:
@react-oauth/google
패키지로 프론트엔드 인증 UI 구현 후auth-code
를 백엔드로 전송 - 백엔드 구현:
google-auth
라이브러리로id_token
검증 및 사용자 인증 처리 - 보안 주의사항:
GOOGLE_CLIENT_SECRET
은.env
파일에 저장하여 노출 방지
섹션별 세부 요약
1. Google Cloud Platform 프로젝트 생성
- 필수 단계:
- Google Cloud Console에서 프로젝트 생성
- OAuth 클라이언트 ID 및 시크릿 생성 (Redirect URI는 postmessage
설정)
- 인증 스크린 설정 및 앱 정보 등록
2. 프론트엔드 구현 (React)
- 라이브러리 설치:
```bash
npm install @react-oauth/google@latest
```
- 인증 흐름:
- useGoogleLogin
훅으로 Google 로그인 버튼 생성
- onSuccess
콜백을 통해 auth-code
를 백엔드로 POST 요청
- flow: 'auth-code'
설정으로 인증 코드 직접 전달
3. 백엔드 설정 (Django)
- 환경 변수 설정:
```python
# .env 파일
GOOGLE_CLIENT_ID='your-google-client-id'
GOOGLE_CLIENT_SECRET='your-google-client-secret'
```
- 라이브러리 설치:
```bash
pip install python-dotenv google-auth
```
4. 인증 서비스 구현
- 토큰 교환 로직:
```python
from google.oauth2 import id_token
from google.auth.transport import requests as google_requests
```
- exchange_code_for_tokens
메서드로 id_token
검증
- 사용자 이메일 및 sub
식별자 추출 후 DB 매칭
5. 사용자 로그인 처리
- 뷰 로직:
```python
@api_view(['POST'])
def google_login(request):
code = json.loads(request.body)['auth_code']
user_id_info = GoogleAuthService.exchange_code_for_tokens(code)
# 사용자 존재 여부 확인 및 토큰 발급
```
- 사용자 모델:
- google_sub
필드 추가로 사용자 식별자 매핑
결론
- 핵심 팁:
- @react-oauth/google
패키지를 사용해 프론트엔드 인증 UI 간소화
- 백엔드에서는 google-auth
라이브러리로 id_token
검증 및 사용자 매핑
- .env
파일을 통해 GOOGLE_CLIENT_SECRET
보안 관리
- 사용자 토큰 발급 시 RefreshToken
으로 재발급 로직 구현 (Django REST Framework 기준)