Setup Basic JWT Authentication
๐งจ Basic application
Using JWT authentication on this library is very easy! Just one import & definition! For testing it, create a basic flask application with a database (SQLAlchemy is recommended).
We also created one basic route that returns a simple JSON response.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
|
Our task is to protect this route by using JWT tokens. For doing this import JWT
main class from our flask_authlib
:
1 |
|
Initialize it bypassing your flask app and sqlalchemy db
as JWT
's arguments:
1 2 3 |
|
Tip
If you look at your routes, you will see new API endpoints on your application. They were added by flask_authlib
's JWT submodule.
For getting a list of routes, I recommended using the flask's CLI.
Yeah, you could do it by python code (using flask. Flask
's url_map
). But, I think it is a very simple & good approach for this task.
In this library, pydantic
is used for the data part (for validating, serializing). Every field of the user's request
the body will be checked & validated!
โจ Run your development server:
1 |
|
or
1 |
|
Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
|
Testing
For testing JWT functionality you can any HTTP clients or python's testing frameworks (unittest, pytest ...). But on this tutorial, I prefer to use postman (useful API development tool).
๐ Registration
-
Basic request:
-
Send empty request body:
-
Checking email validation:
-
Successful registration:
1 2 3 4 5 |
|
๐ Login
-
Send empty request body:
-
Checking email validation:
-
Successful registration:
1 2 3 4 |
|
๐ We have got JWT access token!
๐งฎ Decoding
You can decode this access_token
on jwt.io
- After the decoding process, you can easily get the user's credentials without querying to your database!
CORS
I recommend to you use Flask-Cors
before making API requests to your flask server from the frontend(angular,vue, react ...).
1 |
|
Basic usage:
1 2 3 4 5 6 7 8 9 |
|
P.S You can also use CORS on your
blueprints