ITZone

Integrate FastAPI with authentication using JWT

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:

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:

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.

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

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.

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

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