[python] FastAPI와 Okta를 사용한 인증 구현

FastAPI는 Python으로 구축된 웹 애플리케이션을 위한 빠르고 현대적인 웹 프레임워크입니다. Okta는 안전한 인증과 인가를 위한 클라우드 기반의 플랫폼으로 개발자가 안전한 사용자 인증을 구현할 수 있도록 도와줍니다.

이 블로그 포스트에서는 FastAPI와 Okta를 함께 사용하여 간단한 사용자 인증을 구현하는 방법에 대해 살펴보겠습니다.

목차

  1. FastAPI 애플리케이션 설정
  2. Okta 애플리케이션 설정
  3. FastAPI와 Okta를 연동
  4. 토큰을 활용한 인증
  5. 결론

1. FastAPI 애플리케이션 설정

먼저, FastAPI 애플리케이션을 설정해야 합니다. FastAPI를 사용하여 간단한 웹 애플리케이션을 만든 후에 사용자 인증을 추가할 것입니다.

from fastapi import FastAPI

app = FastAPI()

@app.get("/")
async def read_root():
    return {"message": "Hello, World"}

위와 같이 기본적인 FastAPI 애플리케이션이 설정되었다고 가정합니다.

2. Okta 애플리케이션 설정

다음으로, Okta Developer Console에 로그인하여 “Create App Integration”을 통해 새로운 애플리케이션을 만듭니다. “Single Page App” 유형으로 설정하고 적절한 URI를 추가합니다.

3. FastAPI와 Okta를 연동

FastAPI 애플리케이션과 Okta 애플리케이션을 연동하기 위해서는 클라이언트 키와 인증 서버 URL이 필요합니다. 이 정보를 사용하여 FastAPI 애플리케이션을 구성하여 사용자의 로그인을 처리할 수 있습니다.

from fastapi import FastAPI
from fastapi.security import OAuth2PasswordBearer
from fastapi.openapi.models import OAuthFlows as OAuthFlowsModel

app = FastAPI()

oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token")

# Okta 정보 설정
auth_server = "https://{yourOktaDomain}/oauth2/default"
auth_server_metadata_url = f"{auth_server}/.well-known/oauth-authorization-server"

4. 토큰을 활용한 인증

이제, 획득한 토큰을 사용하여 FastAPI 엔드포인트에서 사용자를 인증할 수 있습니다.

from fastapi import Depends, HTTPException
from jose import JWTError, jwt
from pydantic import ValidationError

async def get_current_user(token: str = Depends(oauth2_scheme)):
    credentials_exception = HTTPException(
        status_code=401,
        detail="Could not validate credentials",
        headers={"WWW-Authenticate": "Bearer"},
    )
    
    try:
        payload = jwt.decode(
            token, 
            public_key, 
            algorithms=[alg]
        )
        username: str = payload.get("username")
        if username is None:
            raise credentials_exception
    except (JWTError, ValidationError):
        raise credentials_exception

5. 결론

FastAPI와 Okta를 함께 사용하여 안전하고 빠른 사용자 인증을 구현하는 방법에 대해 살펴보았습니다. 두 기술을 연동하여 안전하고 신뢰할 수 있는 웹 애플리케이션을 만들 수 있습니다.

더 많은 기능과 세부 설정에 대한 내용은 공식 문서를 참조하시기 바랍니다.

이상으로 FastAPI와 Okta를 사용한 인증 구현에 대한 블로그 포스트를 마치도록 하겠습니다. 감사합니다.