DEV Community

Paul John
Paul John

Posted on

Multiple OAuth2 Schemes FastAPI

Introduction

How do you create multiple OAuth2 token schemes in FastAPI and make sure they are usable in the SwaggerUI auto documentation?

I am building a REST API for a SaaS Loan Management System (LMS) to be used internally by company personnel. I have two kinds of users:

  1. System users - LMS software administrators.
  2. Company users - personnel using the software.

System users can create companies and the first company users. Assign admin role, to allow them to register other company users linked to the same company.

I created two OAuth2 token schemes; admin_oauth2 for system users and user_oauth2 for company users. Separating the authentication models it made it easy to manage. I can create tokens for admins with a simple payload of expiration date and admin ID. And add extra data in the company users' token like the company ID and the user roles for easy role-based access control and authorization.

Creating Multiple OAuth2 Schemes in FastAPI

To create multiple OAuth2 schemes, create two token dependencies; one for the admins, and another for users.

...
user_oauth2 = OAuth2PasswordBearer(
    tokenUrl="/api/v1/login/access-token",
    scheme_name="user_oauth2",
)
UserTokenDep = Annotated[str, Depends(user_oauth2)]

admin_oauth2 = OAuth2PasswordBearer(
    tokenUrl="/api/v1/admin/login/access-token",
    scheme_name="admin_oauth2",
)
AdminTokenDep = Annotated[str, Depends(admin_oauth2)]
Enter fullscreen mode Exit fullscreen mode

That will allow an API to have two OAuth2 authentications depending on the endpoint accessed. Notice the scheme_name argument in the scheme definition. That's an important detail when you have multiple OAuth2 schemes in the same API - that is, if you don't define the scheme name, the authentication token depends on the last endpoint you defined regardless of whether the operation depends on that token or the other token. I spent hours trying to figure out that simple detail. That's all there is to it, the rest are skill issues.

Read Me

Hi there! I am Paul John, a recent software engineering graduate. I recently joined a backend, DevOps and Product Testing internship at HNG Internship to put my learned skills to work and broaden my horizons in Software engineering. My goal is to be able to create a software product from scratch to the maintenance stage (the whole SDLC).

If anything, check out HNG Premium, it delivers added value to the Internship.

Adios!

Top comments (1)

Collapse
 
raajaryan profile image
Deepak Kumar

Hello everyone,

I hope you're all doing well. I recently launched an open-source project called the Ultimate JavaScript Project, and I'd love your support. Please check it out and give it a star on GitHub: Ultimate JavaScript Project. Your support would mean a lot to me and greatly help in the project's growth.

Thank you!