DEV Community

loading...

Build simple API service with Python FastAPI — Part 2

cuongld2 profile image cuongld2 ・2 min read

In the previous-post, I already went over how to set up and create a new user account API service.

In this post, I will show how to do an authenticate API using FastAPI.
Alt Text

I. Hash the real password before save to database:

Previously, we’re doing like this :

Now, we will hash the password using the bycrypt library.

bcrypt is a password hashing function designed by Niels Provos and David Mazières, based on the Blowfish cipher, and presented at USENIX in 1999.[1] Besides incorporating a salt to protect against rainbow table attacks, bcrypt is an adaptive function: over time, the iteration count can be increased to make it slower, so it remains resistant to brute-force search attacks even with increasing computation power.

To install bcrypt library in python, simply

pipenv install bcrypt

And now the code for create new user will look like:

II.Check the input password for authenticate API matching

To be able to do this, we use bcrypt.checkpw from the bcrypt library.

III.Create a token object response if the username and password is correct

1.Define Token Schemas in schemas.py

2.Create an access token by using jwt library

Utilize the jwt library in python by installing it:

pipenv install pyjwt

Then define a method that create an access token from the hashed_password in the database

IV.Wrap altogether and define the authenticate api from main.py
Wrap it altogether to create authenticate API

The below method will validate the username and password, then return the access_token in the response if the username and password is correct.

To run the server, simply click on the run button from IDE, or by command line:

uvicorn main:app --reload

Please check the full sourcecode from github .

Happy coding~~~

Discussion (0)

pic
Editor guide