본문 바로가기
Python/FastAPI

[FastAPI] 스웨거(Swagger) HTTP 기본 인증 `Authorize` 적용하기

by 검은냥냥이 2022. 12. 12.

FastAPI 스웨거(Swagger)

 

Swagger(스웨거)에서 API 호출 시 아이디와 비밀번호를 입력하여 기본 HTTP 인증을 적용할 수 있습니다.

스웨거 문서를 보면 각 API 호출 부분 오른쪽에 자물쇠 아이콘이 생기며, `Execute` 클릭 시에 계정 인증을 요구합니다.

 

Simple HTTP 인증 적용하기

해당 API 호출하는 곳에 `Dpends`으로 아래 코드를 넣어주면 됩니다.

security = HTTPBasic()

credentials: HTTPBasicCredentials = Depends(security)

 

예제

security = HTTPBasic()

router = APIRouter(
    prefix="/token",
    tags=["token"],
    responses={404: {"description": "Not found"}}
)

@router.post("/", tags=["token"], responses=token_argument.TokenCreate)
@router.post("", tags=["token"], include_in_schema=False)
async def TokenCreate(
        credentials: HTTPBasicCredentials = Depends(security),
):
	print(credentials.username)
	print(credentials.password)
    
	# 아이디와 비밀번호 체크 후 리턴
    
	return JSONResponse(status_code=200, content={
 		"access_token": authorize.create_access_token(subject=user.idx).encode().decode('UTF-8'),
		"token_type": "bearer"
	})

 

참고 링크

 

HTTP Basic Auth - FastAPI

HTTP Basic Auth For the simplest cases, you can use HTTP Basic Auth. In HTTP Basic Auth, the application expects a header that contains a username and a password. If it doesn't receive it, it returns an HTTP 401 "Unauthorized" error. And returns a header W

fastapi.tiangolo.com

 

728x90
사업자 정보 표시
레플라 | 홍대기 | 경기도 부천시 부일로 519 화신오피스텔 1404호 | 사업자 등록번호 : 726-04-01977 | TEL : 070-8800-6071 | Mail : support@reafla.co.kr | 통신판매신고번호 : 호 | 사이버몰의 이용약관 바로가기