tech4242
tech4242

Reputation: 2468

FastAPI authentication for multiple services without managed API Gateway

I have a general architectural question regarding a new project with microservices based on FastAPI. Looking at it now it’s really not FastAPI specific but here it goes:

How would you make JWT based authentication work between multiple services assuming the following:

  1. You cannot use managed services from AWS etc. like API Gateway (security requirement)
  2. There is a service for user management, which contains username, password etc. and ideally it would allow for JWT authentication
  3. There are other microservices containing app logic for the users stored in the first microservice (from 2.)

In a monolith app this is easy and in a microservice architecture with API gateways it’s also easy but:

how would you approach this (high level) if things kind of hinge on the user management microservice to hold the relevant user data (and in effect being a gateway of its own) where other services should perform actions for those users (based on the JWT token)

tl;dr How would you extend authentication to the other microservices holding the app logic? I think I am overthinking this one and potentially introducing too much coupling :)

Upvotes: 2

Views: 5079

Answers (1)

Sushi2all
Sushi2all

Reputation: 523

If your authentication/user management service issues a JWT, then your other services can rely on that to provide only the allowed data.

The token issued should contain all relevant security info. Let's say you have three types of user: admin, manager, employee. For sake of simplicity let's say this is the only security criteria (you may have multiple criteria in place).

The token can have a field indicating the user permission. As per the OAuth2 spec this is usually done in a scope field. You can create your own custom fields for it anyways.

With the token you can then call your backend services using it. The services will then:

  • first check the integrity and validity of the token
  • check the token payload for the scope/permissions and provide the data according to it.

See also the official FastAPI tutorial about using scopes for this purpose with a simple dependency injection.


Answering your comment:

JWT is sadly only within Traefik Enterprise

Maybe you're talking about handling the JWT directly in Traefik, but you should have no trouble passing on the authorization header and deal with the authorization check in the backend service. Plus, you can always embed the token in the request body and totally bypass the reverse proxy.

Upvotes: 1

Related Questions