1. 네이버 개발자 센터에서 애플리케이션 등록
- 네이버 개발자 센터에 로그인합니다.
- 애플리케이션을 등록 후 클라이언트 ID, 클라이언트 시크릿 발급
[Node.js] Naver Oauth로 로그인 구현해보기
네이버 로그인 OAuth 신청이 링크에서 로그인 API를 신청할 수 있습니다!https://developers.naver.com/docs/login/api/api.md네이버 로그인 API 명세 - LOGIN네이버 로그인 API 명세 네이버 로그인 API는 네이버 로그
remazitensi.tistory.com
2. FastAPI와 필요한 패키지 설치
pip install fastapi uvicorn httpx python-dotenv
3. FastAPI 애플리케이션 구현
1. .env 파일 생성
먼저, 클라이언트 ID와 클라이언트 시크릿을 환경 변수로 설정합니다. .env 파일을 생성하여 다음과 같이 설정합니다:
NAVER_CLIENT_ID=client_id // 발급 받은 client id
NAVER_CLIENT_SECRET=client_secret // 발급 받은 client secret
2. FastAPI 애플리케이션 작성
from fastapi import FastAPI, Request, Depends, HTTPException
from fastapi.responses import RedirectResponse
from pydantic import BaseModel
import httpx
import os
from dotenv import load_dotenv
# 환경 변수 로드
load_dotenv()
# 환경 변수
NAVER_CLIENT_ID = os.getenv('NAVER_CLIENT_ID')
NAVER_CLIENT_SECRET = os.getenv('NAVER_CLIENT_SECRET')
app = FastAPI()
# 네이버 인증 URL 생성
def get_naver_auth_url():
return (
"https://nid.naver.com/oauth2.0/authorize"
"?response_type=code"
f"&client_id={NAVER_CLIENT_ID}"
"&redirect_uri=http://localhost:8000/callback"
"&state=your_state_parameter"
)
# 네이버 토큰 요청
async def get_naver_token(code: str):
token_url = "https://nid.naver.com/oauth2.0/token"
headers = {
"Content-Type": "application/x-www-form-urlencoded"
}
params = {
"grant_type": "authorization_code",
"client_id": NAVER_CLIENT_ID,
"client_secret": NAVER_CLIENT_SECRET,
"code": code,
"state": "your_state_parameter"
}
async with httpx.AsyncClient() as client:
response = await client.post(token_url, headers=headers, data=params)
response.raise_for_status()
return response.json()
# 네이버 사용자 정보 요청
async def get_naver_user_info(access_token: str):
user_info_url = "https://openapi.naver.com/v1/nid/me"
headers = {
"Authorization": f"Bearer {access_token}"
}
async with httpx.AsyncClient() as client:
response = await client.get(user_info_url, headers=headers)
response.raise_for_status()
return response.json()
@app.get("/")
async def root():
auth_url = get_naver_auth_url()
return RedirectResponse(auth_url)
@app.get("/callback")
async def callback(request: Request):
code = request.query_params.get("code")
state = request.query_params.get("state")
if state != "your_state_parameter":
raise HTTPException(status_code=400, detail="Invalid state parameter")
# 네이버에서 발급된 액세스 토큰을 요청
token_response = await get_naver_token(code)
access_token = token_response.get("access_token")
if not access_token:
raise HTTPException(status_code=400, detail="Failed to get access token")
# 액세스 토큰을 사용하여 사용자 정보를 요청
user_info = await get_naver_user_info(access_token)
return user_info
4. 서버 실행
uvicorn your_filename:app --reload
http://localhost:8000에 접속하면 네이버 로그인 페이지로 리다이렉트됩니다.
로그인 후, 네이버는 http://localhost:8000/callback으로 리다이렉트하며, 여기서 액세스 토큰을 얻어 사용자 정보를 반환
설명
- 네이버 인증 URL 생성: get_naver_auth_url 함수는 네이버 로그인 페이지로 리다이렉트할 URL을 생성
- redirect_uri는 네이버 개발자 센터에서 등록한 리디렉션 URI와 일치해야 합니다.
- 토큰 요청: 사용자가 로그인 후 반환된 code를 사용하여 액세스 토큰을 요청합니다. 이 토큰을 사용하여 사용자 정보를 요청할 수 있습니다.
- 사용자 정보 요청: 액세스 토큰을 사용하여 네이버 사용자 정보를 가져옵니다.
- 서버 실행: uvicorn을 사용하여 FastAPI 서버를 실행
'Framework > FastAPI' 카테고리의 다른 글
FastAPI 기반 실시간 알림 서비스 비교 (0) | 2024.08.25 |
---|