Below you will find pages that utilize the taxonomy term “Swagger”
Swagger + OAuth2
목표
- swagger에서
- google oauth를 swagger authorize ui에 적용
- 인증된 Token을 각 API에서 Header에 설정 할 수 있도록
custom open api
from fastapi.security.oauth2 import OAuth2AuthorizationCodeBearer
from fastapi.openapi.models import OAuthFlows as OAuthFlowsModel, OAuthFlowAuthorizationCode
from fastapi.openapi.models import SecurityScheme as SecuritySchemeModel
from fastapi.openapi.utils import get_openapi
# --------------------------------------------------------------
# Google oAuth2
CLIENT_ID = "...알아서"
CLIENT_SECRET = "...알아서"
TOKEN_URL = "...알아서"
AUTHORIZATION_URL = "...알아서"
class OAuth2Google(OAuth2AuthorizationCodeBearer):
def __init__(self):
super().__init__(authorizationUrl=AUTHORIZATION_URL, tokenUrl=TOKEN_URL)
oauth2_scheme = OAuth2Google()
# --------------------------------------------------------------
# Auth for Swagger
def custom_openapi():
if app.openapi_schema:
return app.openapi_schema
openapi_schema = get_openapi(
title="FastAPI with Google OAuth2",
version="1.0.0",
description="This is a FastAPI application integrating Google OAuth2",
routes=app.routes,
)
openapi_schema["components"]["securitySchemes"] = {
"OAuth2Google": {
"type": "oauth2",
"flows": {
"authorizationCode": {
"authorizationUrl": AUTHORIZATION_URL,
"tokenUrl": TOKEN_URL,
"scopes": {
"openid": "OpenID Connect",
"email": "Access to your email address",
"profile": "Access to your basic profile info"
}
}
}
}
}
app.openapi_schema = openapi_schema
return app.openapi_schema
# open api 변경
app.openapi = custom_openapi
이런 간단한 코드로 아래와 같은 훌륭한 화면을 도출 해 낼 수 있었으나.
Swagger에 Google oAuth를 적용하며
Swagger에 Google oAuth를 적용하는 시도를 하고있었다.
대충 다 맞게 적용한거 같은데 자꾸만 redirect_uri_mismatch를 반환하는 것이다.
![]() |
|---|
| Swagge에서 보여주는 메시지 |
Google Console에서 설정하려고 아무생각없이 긁었는데.. 그게 문제다.
http://localhost:9031/docs/oauth2-redirect flowName=GeneralOAuthFlow
중간에 공백이 왜 있을까? 고민을 살짝 했으나.. 출력의 문제라고 판단하고
http://localhost:9031/docs/oauth2-redirect?flowName=GeneralOAuthFlow
당연히 될 일이 아니다.
결론은 아래와 같다.
http://localhost:9031/docs/oauth2-redirect
안내 메시지의 출력시 개행은 항상 중요하다.
요청 세부정보:
redirect_uri=http://localhost:9031/docs/oauth2-redirect
flowName=GeneralOAuthFlow
