Integrate FastAPI with authentication using JWT

Tram Ho

FastAPI JWT

Login with json-web-token in Fastapi

Intro: Quick guide to setup login with JWT in Fastapi

Thinking: With the usual serverless mechanism, the steps of user authentication in a service backend via API usually take place as follows:

  • User provides username + password and calls API login to get authentication code (JWT token)
  • User uses the JWT authentication code provided by the system, add this code in the header of each request so that the system checks every time the API calls.

As we all know or on the homepage of FastAPI wrote

FastAPI is a modern, fast (high-performance), web framework for building APIs with Python 3.6+ based on standard Python type hints.

Here I will write a quick setup to install using JWT in FastAPI. Mainly we have 2 steps:

  • Write a Login API to get JWT token
  • Write an API to get any data, JWT token is required to get data

Step1: Setup a FastAPI service

First, install fastapi and create the file main.py and add a few lines of code to make sure FastAPI works

At the CLI interface, run command

Open a web browser to check http://localhost:8000/docs

Call to try the API to see if it works

Step2: Create login form

Using Pydantic to create a login form, now the login form only needs 2 fields: username and password.

  • More classes LoginRequest
  • Add request_data to login function & use print to show request_data on CLI

Check the webrower, the request body already shows the form

Click Try it out, try entering username & password: test/test and check CLI

Step3: function verify_password

Enter username, password of course will need a function to check if username/password is correct, write a simple function to check username and password is equal to admin/admin

The logic is if username/password = admin/admin then return Success, otherwise return 404 – User not found
Test the case not found

Step4: Generate & return token

When entering correct username/password, login api needs to return JWT token, so now we write gentoken

  • Install PyJWT, to generate jwt token, we need to use PyJWT library. Open CLI and run:

  • Create functions generate_token, return value of this function instead of return ‘Success’

Try calling the API and see the result

The result is a token chain consisting of 3 parts

Step5: Required header Token when calling API books

To add token input form in Swagger and check required token, FastAPi has built-in utility lib, HTTPBearer.

  • In security.py, to add reusable_oauth2 is an instance of HTTPBearer
  • Use reusable_oauth2 as dependencies in the books . API

Back on the webrowser, you can see the lock icon and the Authorize button in the upper right corner

Call to try API /books  without entering token, will see response "detail": "Not authenticated"

Step6: validate_token

After briefly understanding the use of HTTPBearer, we use it to get token and check validity

  • In security.py add function validate_token
  • Use validate_token as dependencies in the books . API

Go back to the webrowser, call API login to get the token and enter that token to call API /books  and see how it goes.

Conclusion

Integrating JWT into FastAPI is quite simple, the important thing is that we need to know how to use it HTTPBearer and dependencies are the built-in tools provided by the framework.
Also, if possible, you can learn more about how lib works PyJWT in https://pyjwt.readthedocs.io/en/stable/

Run this project

To run this project:

Share the news now