파이썬 FastAPI와 JWT를 활용한 다중 인증 시스템 구현 방법

FastAPI JWT

개요

다중 인증 시스템은 사용자가 여러 가지 인증 방법을 통해 로그인하고 접근할 수 있는 시스템입니다. 이 글에서는 파이썬 웹 프레임워크인 FastAPI와 JWT(Json Web Token)를 사용하여 다중 인증 시스템을 구현하는 방법을 소개합니다. JWT는 사용자의 로그인 정보를 안전하게 전달하고 인증을 관리하는 데에 유용한 메커니즘을 제공합니다.

FastAPI와 JWT 설치

먼저 FastAPI와 JWT를 설치해야 합니다. 아래 명령어를 사용하여 필요한 패키지를 설치합니다.

pip install fastapi
pip install pyjwt

FastAPI 애플리케이션 설정

FastAPI 애플리케이션을 만들고 JWT 인증을 위한 설정을 추가해야 합니다. 다음과 같이 코드를 작성합니다.

from fastapi import FastAPI, Depends, HTTPException
from fastapi.security import OAuth2PasswordBearer
from pydantic import BaseModel
from datetime import datetime, timedelta
import jwt
from passlib.context import CryptContext

app = FastAPI()

class User(BaseModel):
    username: str
    password: str

class Token(BaseModel):
    access_token: str
    token_type: str

oauth2_scheme = OAuth2PasswordBearer(tokenUrl="/login")

pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
secret_key = "mysecretkey"
algorithm = "HS256"
access_token_expires_minutes = 30

# JWT 토큰 생성 함수
def create_access_token(data: dict, expires_delta: timedelta):
    to_encode = data.copy()
    expire = datetime.utcnow() + expires_delta
    to_encode.update({"exp": expire})
    encoded_jwt = jwt.encode(to_encode, secret_key, algorithm=algorithm)
    return encoded_jwt

# 사용자 인증 함수
def get_user(username: str):
    # 사용자 인증 로직 추가
    # 예를 들면 데이터베이스에서 사용자 정보를 조회하는 작업을 수행할 수 있습니다.
    return User(username="testuser", password="testpassword")

# 로그인 엔드포인트
@app.post("/login", response_model=Token)
async def login(user: User):
    db_user = get_user(user.username)
    if not db_user:
        raise HTTPException(status_code=400, detail="Incorrect username or password")
    if not pwd_context.verify(user.password, db_user.password):
        raise HTTPException(status_code=400, detail="Incorrect username or password")
    access_token_expires = timedelta(minutes=access_token_expires_minutes)
    access_token = create_access_token(
        data={"sub": user.username}, expires_delta=access_token_expires
    )
    return {"access_token": access_token, "token_type": "bearer"}

# 보호되는 API 엔드포인트
@app.get("/protected")
async def protected_route(token: str = Depends(oauth2_scheme)):
    try:
        payload = jwt.decode(token, secret_key, algorithms=[algorithm])
        if payload.get("sub") is None:
            raise HTTPException(status_code=403, detail="Invalid authentication credentials")
        return {"message": "Success"}
    except jwt.ExpiredSignatureError:
        raise HTTPException(status_code=403, detail="Invalid authentication credentials")

위 코드에서는 FastAPI 애플리케이션을 생성하고, User 모델과 Token 모델을 정의합니다. OAuth2PasswordBearer를 사용하여 토큰을 가져오고, CryptContext를 사용하여 비밀번호를 암호화합니다. 또한, JWT 토큰 생성과 사용자 인증을 위한 함수를 구현합니다.

실행

위 코드를 main.py 파일에 저장하고 다음과 같이 실행합니다.

uvicorn main:app --reload

이제 FastAPI 애플리케이션이 실행중이며, http://127.0.0.1:8000/docs에 접속하여 API 문서를 확인할 수 있습니다.

결론

이렇게 FastAPI와 JWT를 활용하여 파이썬에서 다중 인증 시스템을 구현하는 방법을 소개했습니다. FastAPI는 빠른 속도와 간편한 사용성으로 인기 있는 웹 프레임워크이며, JWT는 강력한 보안과 토큰 기반의 인증 메커니즘을 제공합니다. 이를 조합하여 다양한 인증 방법을 지원하는 다중 인증 시스템을 구현할 수 있습니다.

#파이썬 #FastAPI #JWT #다중인증