Multiple OAuth2 Schemes FastAPI

namestarlit

Paul John

Posted on July 1, 2024

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!

💖 💪 🙅 🚩
namestarlit
Paul John

Posted on July 1, 2024

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

Multiple OAuth2 Schemes FastAPI
fastapi Multiple OAuth2 Schemes FastAPI

July 1, 2024

Multiple OAuth2 Schemes FastAPI
fastapi Multiple OAuth2 Schemes FastAPI

July 1, 2024