Authenticate the user credential is a must step for any API services.
By the end of this post, you can create an authenticate API that looks like this
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. 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
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
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 .