Skip to content

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
from flask import Flask
from flask_sqlalchemy import SQLAlchemy

app = Flask(__name__)
db = SQLAlchemy(app)

app.config["SQLALCHEMY_DATABASE_URI"] = "sqlite:///database.sqlite"


@app.route("/")
def home():
    return {"message":"It should be protected!"}


if __name__ == "__main__":
    app.run(debug=True) # just run this python code and it will be executed

Our task is to protect this route by using JWT tokens. For doing this import JWT main class from our flask_authlib:

1
from flask_authlib import JWT

Initialize it bypassing your flask app and sqlalchemy db as JWT's arguments:

1
2
3
from flask_authlib import JWT

auth = JWT(app,db)

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.

FLASK_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
$ python server.py

or

1
$ flask run

Code:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
from flask import Flask
from flask_sqlalchemy import SQLAlchemy


app = Flask(__name__)
db = SQLAlchemy(app)

app.config["SQLALCHEMY_DATABASE_URI"] = "sqlite:///database.sqlite"

auth = JWT(app, db)

@app.route("/")
def home():
    return {"message":"It should be protected!"}

if __name__ == "__main__":
    app.run(debug=True)

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: BASIC_REQUEST

  • Send empty request body: EMPTY_REQUEST

  • Checking email validation: VALID_REQUEST

  • Successful registration:

1
2
3
4
5
{
    email:str # EmailStr on pydantic
    password:str
    username:str
}

VALID_REQUEST

๐Ÿ”“ Login

  • Send empty request body: EMPTY_REQUEST

  • Checking email validation: VALID_REQUEST

  • Successful registration:

1
2
3
4
{
    password:str
    username:str
}

VALID_REQUEST

๐Ÿš€ We have got JWT access token!

๐Ÿงฎ Decoding

You can decode this access_token on jwt.io

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
pip install -U flask-cors

Basic usage:

1
2
3
4
5
6
7
8
9
from flask import Flask
from flask_cors import CORS

app = Flask(__name__)
CORS(app)

@app.route("/")
def root():
  return {"success":True}

P.S You can also use CORS on your blueprints

Documentation

Back to top