[HELP | BUG] Multiple OAUTH2 schemes for different user types #11492
-
First Check
Commit to Help
Example Codeoauth2_scheme_recruit = OAuth2PasswordBearer(tokenUrl="/auth/recruit/token")
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="/auth/token")
# above I am using different token url
async def get_current_recruit_user(
token: Annotated[str, Depends(oauth2_scheme_recruit)],
user_service: RecruitUserService = Depends(get_recruit_user_service),
):
async def get_current_normal_user(
token: Annotated[str, Depends(oauth2_scheme)],
user_service: UserService = Depends(get_user_service),
):
# depending on normal user
@auth_router.get("/protected-route")
async def protected_route(user: UserModel = Depends(get_current_normal_user)):
print("inside protected_route")
# depending on recruit user defined above
@recruit_auth_router.get("/protected-route2")
async def protected_route(user = Depends(get_current_recruit_user)):
print("inside protected_route") DescriptionI have job based application where all recruiter based routes should get token from /auth/recruit/token and all other users should get token from /auth/token. When having multiple oauth2 schemes, I expected it to show different url in OPENAPI docs based on how I call these functions in fastapi depends. but it always shows /auth/recruit/token only. NOTE: I have two views.py file, one for normal user and other for recruiter, and I use API ROUTER in fastapi for both and combine them with fastapi include router Operating SystemWindows Operating System DetailsWindows 11 FastAPI Version0.110.0 Pydantic Version2.6.4 Python Version3.10.11 Additional Contextit always points to /auth/recruit/token not matter what oauth2 scheme I depend upon |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments
-
Hi! fastapi/fastapi/security/oauth2.py Line 376 in 1d41a7d Just specify
There is a PR (#4791) that fixes the same issue in APIKey, but it should be slightly modified and merged. |
Beta Was this translation helpful? Give feedback.
-
got it resolved, thanks for your help. |
Beta Was this translation helpful? Give feedback.
Hi!
That's because if you don't specify
scheme_name
for security scheme, FastAPI uses it's class name as a default value. And it's 'OAuth2PasswordBearer' for both of them.fastapi/fastapi/security/oauth2.py
Line 376 in 1d41a7d
Just specify
scheme_name
parameter:There is a PR (#4791) that fixes the same issue in APIKey, but it should be slightly modified and merged.