본문 바로가기

Data/MLOps

[FastAPI] 인증 정보 추가하기

반응형

 

 

FastAPI를 사용하면서 모르는 외부 인원이 접근하여 내가 만든 REST API를 마구잡이 실행하는걸 걱정할수가 있는데, FastAPI에서 제공하는 인증관련 요소를 활용하면 막을수있다.

 

아래는 정말 간단한 예시이고, 좀더 안전한 방식을 원한다면 문서를 정독을 해야할것같다.

https://fastapi.tiangolo.com/advanced/security/http-basic-auth/

 

HTTP Basic Auth - FastAPI

FastAPI framework, high performance, easy to learn, fast to code, ready for production

fastapi.tiangolo.com

 

양질의 블로그 글을 위해 바로 예시 코드를 공유하자면...

import time
from typing import Union

from fastapi import Depends, FastAPI, HTTPException, status
from fastapi.security import HTTPBasic, HTTPBasicCredentials
from typing_extensions import Annotated


app = FastAPI()
security = HTTPBasic()

def check_this_request(credentials: Annotated[HTTPBasicCredentials, Depends(security)]):
    correct_username = "jaeyung"
    correct_password = "jaeyungps"

    current_username = credentials.username
    current_password = credentials.password

    if correct_username == current_username and correct_password == current_password:
        return True
    else:
        raise HTTPException(
            status_code=status.HTTP_401_UNAUTHORIZED,
            detail="Incorrect username or password",
            headers={"WWW-Authenticate": "Basic"},
        )

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

@app.get("/security")
async def security_test(return_value: Annotated[bool, Depends(check_this_request)]):
    return return_value

 

위와 같이 코드를 작성하고 FastAPI 를 실행시켜보자

uvicorn main:app --reload

 

실행과 동시에 FastAPI에서 기본적으로 제공하는 docs 에 접속하면 아래와같이 표시된다. 특히 우리가 인증을 걸어둔 REST API한개는 자물쇠 모양이 생성되어있는데.

 

docs페이지에서 "Try it out" -> "Execute"를 클릭하면 인증을 하라는 알람창이 뜨게된다.

 

여기서 우리가 사전에 정의한 아이디 패스워드를 기입하면 정상적으로 FastAPI를 사용하게 된다.

만약 틀리면 아래와같이 401 에러 로그가 발생하게 된다.

 

참고로 curl구문으로 요청할때도 동일하게 아이디 패스워드 정보를 넘겨줘야지만 FastAPI를 사용 할 수 있다. 아래는 curl 예시다.

# 인증정보가 없을경우
curl -X 'GET' \
  'http://127.0.0.1:8000/security' \
  -H 'accept: application/json'
  
# 출력 -> {"detail":"Not authenticated"}

# 인증정보가 있을경우
curl -X 'GET' -u jaeyung:jaeyungps \
  'http://127.0.0.1:8000/security' \
  -H 'accept: application/json'
# 출력 -> true
반응형