- Published on
FastAPI 인증/인가 구현하기: JWT부터 OAuth2까지! 🔐
- Authors
- Name
- devnmin
FastAPI로 안전한 인증 시스템 구축하기 🔒
안녕하세요! 오늘은 FastAPI로 인증/인가 시스템을 구축하는 방법을 알아볼 건데요. 보안이 중요하다고 해서 어려울 필요는 없죠! 재미있게 시작해봅시다! 😎
1. 필요한 패키지 설치하기 📦
pip install python-jose[cryptography] passlib[bcrypt] python-multipart
# python-jose: JWT 토큰 생성/검증
# passlib: 비밀번호 해싱
# python-multipart: form 데이터 처리
2. JWT 토큰 설정하기 🎟️
# auth/token.py
from datetime import datetime, timedelta
from jose import JWTError, jwt
from fastapi import HTTPException
# 비밀키는 꼭 환경변수로 관리하세요! 🤫
SECRET_KEY = "your-super-secret-key-here"
ALGORITHM = "HS256"
ACCESS_TOKEN_EXPIRE_MINUTES = 30 # 토큰 유효기간
def create_access_token(data: dict):
to_encode = data.copy()
# 토큰 만료시간 설정 (30분 뒤에 만료될 거예요! ⏰)
expire = datetime.utcnow() + timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES)
to_encode.update({"exp": expire})
# JWT 토큰 생성! 🎉
encoded_jwt = jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM)
return encoded_jwt
3. 비밀번호 해싱하기 🔑
# auth/hashing.py
from passlib.context import CryptContext
# bcrypt 알고리즘 사용 (매우 안전해요! 💪)
pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
def verify_password(plain_password, hashed_password):
return pwd_context.verify(plain_password, hashed_password)
def get_password_hash(password):
return pwd_context.hash(password)
4. 의존성으로 현재 사용자 가져오기 👤
# dependencies.py
from fastapi import Depends, HTTPException, status
from fastapi.security import OAuth2PasswordBearer
from jose import JWTError, jwt
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token")
async def get_current_user(token: str = Depends(oauth2_scheme)):
credentials_exception = HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="토큰이 유효하지 않아요! 😢",
headers={"WWW-Authenticate": "Bearer"},
)
try:
# 토큰 디코딩
payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
username: str = payload.get("sub")
if username is None:
raise credentials_exception
except JWTError:
raise credentials_exception
# 사용자 정보 가져오기
user = get_user(username)
if user is None:
raise credentials_exception
return user
5. 로그인 엔드포인트 구현하기 🚪
# main.py
from fastapi import FastAPI, Depends, HTTPException
from fastapi.security import OAuth2PasswordRequestForm
app = FastAPI()
@app.post("/token")
async def login(form_data: OAuth2PasswordRequestForm = Depends()):
# 사용자 인증
user = authenticate_user(form_data.username, form_data.password)
if not user:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="아이디나 비밀번호가 틀렸어요! 😅",
headers={"WWW-Authenticate": "Bearer"},
)
# 토큰 생성! 🎟️
access_token = create_access_token(
data={"sub": user.username}
)
return {"access_token": access_token, "token_type": "bearer"}
6. 보호된 엔드포인트 만들기 🛡️
@app.get("/users/me")
async def read_users_me(current_user = Depends(get_current_user)):
return current_user
@app.get("/super-secret")
async def get_secret(current_user = Depends(get_current_admin_user)):
return {"message": "축하해요! 비밀 정보를 찾았어요! 🎉"}
7. OAuth2 소셜 로그인 추가하기 🌐
from fastapi_oauth.clients import GoogleOAuth2, GithubOAuth2
# Google 로그인
@app.get("/login/google")
async def login_google():
return await google_oauth.get_login_redirect()
@app.get("/auth/google")
async def auth_google(code: str):
token = await google_oauth.get_access_token(code)
user_data = await google_oauth.get_user_info(token)
# 사용자 정보로 회원가입 또는 로그인 처리
return {"message": f"환영해요, {user_data['name']}님! 👋"}
보안 팁! 🔒
HTTPS 사용하기
- 토큰은 꼭 HTTPS로 전송해야 해요!
- 프로덕션에서는 필수입니다!
토큰 관리
# 리프레시 토큰 사용하기 refresh_token = create_refresh_token(user.id)
Rate Limiting 적용
from slowapi import Limiter from slowapi.util import get_remote_address limiter = Limiter(key_func=get_remote_address) @app.post("/login") @limiter.limit("5/minute") # 1분에 5번만 시도할 수 있어요! 🚫 async def login(): # ... 로그인 로직
자주 하는 실수들 🚨
토큰 만료시간을 너무 길게 설정
- 30분에서 2시간 정도가 적당해요!
비밀키를 코드에 하드코딩
- 환경변수로 관리하세요!
평문 비밀번호 사용
- 꼭 해시해서 저장하세요!
다음 단계로... 🎯
다음 시간에는... FastAPI 애플리케이션 배포하는 방법을 알아볼 거예요! Docker와 함께요! 🐳
유용한 자료들 📚
Pro Tip: JWT 토큰은 세션과 다르게 서버에 상태를 저장하지 않아요! 이게 바로 FastAPI가 빠른 이유 중 하나죠! 😎