SlideShare a Scribd company logo
Flask JWT
Authentication
Tutorial
www.bacancytechnology.com
In the Flask JWT Authentication tutorial, we
will build a demo application together; learn
about the Flask framework, REST APIs, and
Auth Token Authentication. If this is your first
time implementing token authentication ib
Flask, don’t worry! After going through this
tutorial, your doubts would be solved and you
won’t be a beginner anymore. For simplifying
the tutorial, I have classified it into various
sections.
CONTENTS
1. What are JSON Web Tokens?
2. What is Flask Framework?
3. Goal of Flask JWT Authentication Tutorial
4. Step-by-step Tutorial to Implement Flask
JWT Authentication
5. Conclusion
What are JSON
Web Tokens?
Serialized- This type is used when you’re
transferring information to the network via
every request and response. It contains a
payload, header, and signature.
JSON Web Tokens (JWT) is a secure and compact
way to transmit data between two parties with
the help of JSON objects.
JSON web token consists of three parts-
Payload
Header
Signature
JSON uses two different structure types for
transmitting data.
Deserialized- This type is used when you’re
reading/writing information to the token. It
contains a payload and header.
What is Flask
Framework?
Flask is a python based micro-framework used
to build rest API. A “micro-framework” neither
implies that your entire web app has to fit into a
single Python code file nor Flask lacks
functionality. The core idea of the Flask
framework is to keep things simple but
extensible. It allows developers to add custom
extensions for database integration,
authentication, session management, and all
the other backend systems based on
preferences.
Goal of Flask
JWT
Authentication
Tutorial
Before knowing how to implement Flask JWT
Authentication, let’s see the video and know
what we will build.
Watch Video
Step-by-step
Tutorial to
Implement
Flask JWT
Authentication
Ubuntu 20.04 OS
Postman
Python 3.8+
Let’s start the implementation of the Flask JWT
Authentication. Here’s my system setup and
Flask JWT example for better understanding:
Virtual environment Set Up using virtualenv
A virtual environment ensures that none of the
packages used in the project conflict with
system packages. It is also a good practice to
avoid polluting your OS by installing every
package directly onto the OS.
We will use the virtualenv command for setting
up a new virtual environment in our project.
We will need pip command to proceed further.
If you don’t have pip installed on your system,
use the below command for installing pip on
your system.
sudo apt-get install python3-pip
Once you have the pip command installed on
your system, run the following command to
install virtualenv.
pip install virtualenv
Now, run the mkdir command to create a new
folder/directory for storing the virtual
environment.
mkdir myflaskproject
Change the current working directory to
myflaskproject:
cd myflaskproject
Inside the myflaskproject directory, create a
new virtual environment with the help of the
virtualenv tool:
virtualenv venv
After you have successfully created a virtual
environment using the irtualenv tool, activate
the virtual environment using the following
command:
Now, it’s time to install the packages we need
for this project to build Python REST API
authentication token and other necessary
packages for this API project such as-
Install packages using pip
flask
pyjwt
flask-sqlalchemy
datetime
uuid
An efficient way of doing this is by creating a
requirements.txt file and listing all the packages
into it. You can also declare the versions of the
packages wherever necessary.
flask==1.1.2
pyjwt==2.0.0
datetime
uuid
Flask-SQLAlchemy
Now, use this file to install all the listed
packages with pip.
pip install -r requirements.txt
Set up a database
Users
Books
To keep this simple, we will use SQLite for this
project. Use the following code to install SQLite.
sudo apt-get update
sudo apt-get install sqlite3
Create a database named “bookstore” consisting
of two tables-
Users table will store registered users. We will
also keep a check, allowing only the registered
users to access the Books table.
Books table will store the details and
information about books, such as the book’s
name, author of the book, publication of the
book, and submitted by the registered users.
Create the database:
sqlite3 bookstore.db
Run the below command for checking if you
have successfully created the database or not:
.databases
Create a new file named “app.py” in the
myflaskproject directory or run this command
in your terminal:
touch app.py
NOTE- while executing commands in the
terminal, make sure you do it inside the virtual
environment named “venv” we created earlier.
Now, paste the following code inside the python
file named app.py:
app.py
from flask import Flask, jsonify, make_response,
request
from werkzeug.security import
generate_password_hash,check_password_hash
from flask_sqlalchemy import SQLAlchemy
from functools import wraps
import uuid
import jwt
import datetime
Let’s see the purpose of importing the packages
mentioned above.
Packages from Flask framework
request – For keeping track of the associated
data at the request level during a request.
jsonify – We will need jsonify to receive the
output responses in JSON format and request
flask_sqlalchemy-This package will help us to
integrate SQLAlchemy features into the Flask
framework. SQLAlchemy is the Object
Relational Mapper & Python SQL toolkit that
provides full power and flexibility of SQL to
developers.
check_password_hash- For checking the
user’s password. It compares the password
provided by the user with the one stored in
the database.
⦿Packages from Flask framework
⦿Package from SQLAlchemy
⦿Package from werkzeug.security
The package datetime will help us manipulate
date and time as date objects. We need this
module because python does not have any
data type to support dates.
Universal Unique Identifiers create random
ID numbers for users. The uuid is a very
useful package, especially for such database
engines that do not support incremental
primary key features. Also, it is better to use
multi-character alpha-numeric values as IDs
instead of using linearly incremental numeric
IDs.
⦿datetime
⦿uuid
Now it’s time to configure settings for the
Bookstore API inside the app.py file using the
below code.
app.py
app = Flask(__name__)
app.config['SECRET_KEY']='004f2af45d3a4e161a7d
d2d17fdae47f'
app.config['SQLALCHEMY_DATABASE_URI']='sql
ite://///home/manthantrivedi/Documents/Bacan
cy/bacancy_blogs/flask_auth/myflaskproject/bo
okstore.db'
app.config['SQLALCHEMY_TRACK_MODIFICATI
ONS'] = True
db = SQLAlchemy(app)
Here, the value assigned to the config variable
‘SECRET KEY’ can be auto-generated using a
python library named ‘secrets.’ We can simply run
the following code in your terminal to generate
this value, as shown below.
Now, we will create two models for the Books
and Users table.
app.py
class Users(db.Model): id =
db.Column(db.Integer, primary_key=True)
public_id = db.Column(db.Integer) name =
db.Column(db.String(50)) password =
db.Column(db.String(50)) admin =
db.Column(db.Boolean)
class Books(db.Model): id =
db.Column(db.Integer, primary_key=True)
user_id = db.Column(db.Integer,
db.ForeignKey('users.id'), nullable=False) name
= db.Column(db.String(50), unique=True,
nullable=False) Author =
db.Column(db.String(50), unique=True,
nullable=False) Publisher =
db.Column(db.String(50), nullable=False)
book_prize = db.Column(db.Integer)
Moving ahead with Flask-JWT Authentication
Tutorial. Use the below code for creating tables
for both tables:
from app import db
db.create_all()
Generate Users and Books Tables
Now, go to the app.py file and create the other
functions required.
The “login_user” function will generate tokens
to allow only registered users to access and
manipulate a set of API operations against the
Books table.
Simply paste the following code after the
database model for both tables.
def token_required(f):
@wraps(f) :
decorator(*args, **kwargs):
token = None
if 'x-access-tokens' in request.headers:
token = request.headers['x-access-tokens']
if not token:
return jsonify({'message': 'a valid token is
missing'})
try:
data = jwt.decode(token,
app.config['SECRET_KEY'], algorithms=
["HS256"])
current_user =
Users.query.filter_by(public_id=data['public_i
d']).first()
except: return jsonify({'message': 'token is
invalid'})
return f(current_user, *args, **kwargs)
return decorator
This code is actually a special function. This
function will create a custom decorator with the
code required to create and validate tokens.
Python provides a very amazing feature named
function decorators. These function decorators
allow very neat features for web development.
In Flask, each view is considered as a function,
and decorators are used for injecting additional
functionality to one or more functions. In this
case, the functionality handled by this custom
decorator will be to create and validate tokens.
In this step, we will generate a route for
allowing users to register for the Books API
using their name and password. With this route,
we will create a view to encrypt the user’s
password, store the new user’s details into the
database, and return a success message.
Creating routes for Users tables
Again, inside the app.py file, paste the following
code after token_required(f) function:
@app.route('/register', methods=['POST']) def
signup_user(): data = request.get_json()
hashed_password =
generate_password_hash(data['password'],
method='sha256') new_user =
Users(public_id=str(uuid.uuid4()),
name=data['name'],
password=hashed_password, admin=False)
db.session.add(new_user) db.session.commit()
return jsonify({'message': 'registered
successfully'})
Now, generate another route that will allow all
the registered users to log in. With the login
route, we will create a view to handle the user
login feature. When a user logs in, the entered
password is matched with the user’s stored
password. If the password matches
successfully, a random token is generated to
access the Bookstore API. For instance, we will
keep the expiration time for this random token
to be 45 minutes.
You can simply update your file with the below-
mentioned code beneath the registered route
we created in the previous step:
@app.route('/login', methods=['POST']) def
login_user(): auth = request.authorization if not
auth or not auth.username or not
auth.password: return make_response('could
not verify', 401, {'Authentication': 'login
required"'}) user =
Users.query.filter_by(name=auth.username).fir
st() if check_password_hash(user.password,
auth.password): token = jwt.encode({'public_id'
: user.public_id, 'exp' :
datetime.datetime.utcnow() +
datetime.timedelta(minutes=45)},
app.config['SECRET_KEY'], "HS256") return
jsonify({'token' : token}) return
make_response('could not verify', 401,
{'Authentication': '"login required"'})
Create another route in the app.py file to get all
the registered users. This route verifies the
registered users in the Users table and provides
the output in JSON format. Use the below code
after the login route.
@app.route('/users', methods=['GET']) def
get_all_users(): users = Users.query.all() result =
[] for user in users: user_data = {}
user_data['public_id'] = user.public_id
user_data['name'] = user.name
user_data['password'] = user.password
user_data['admin'] = user.admin
result.append(user_data) return jsonify({'users':
result})
Let’s create routes for the Books table. These
routes will allow users to retrieve all the Books
in the database and delete them. We will also
implement a mandatory check to verify the
users having valid tokens can only perform any
API requests.
Define a route for all the registered users to
create a new book. The following code creates a
route to meet this requirement:
Creating routes for Books tables
@app.route('/book', methods=['POST'])
@token_required def
create_book(current_user): data =
request.get_json() new_books =
Books(name=data['name'],
Author=data['Author'],
Publisher=data['Publisher'],
book_prize=data['book_prize'],
user_id=current_user.id)
db.session.add(new_books) db.session.commit()
return jsonify({'message' : 'new books created'})
Now, create a route to allow a logged in user
with valid token to get all the books in the
Books table as shown below:
@app.route('/books', methods=['GET'])
@token_required
def get_books(current_user):
books =
Books.query.filter_by(user_id=current_user.id)
.all() output = [] for book in books: book_data =
{} book_data['id'] = book.id book_data['name'] =
book.name book_data['Author'] = book.Author
book_data['Publisher'] = book.Publisher
book_data['book_prize'] = book.book_prize
output.append(book_data)
return jsonify({'list_of_books' : output}
Finally, we will create the last route to delete a
specific book. We will create a view responsible
for handling requests made to delete an existing
record in the Books table. It will verify and
delete the given record from the DB, if exists.
The below-mentioned code can be implemented
after the route allows the user to retrieve a list
of books.
@app.route('/books/<book_id>',
methods=['DELETE'])
@token_required
def delete_book(current_user,
book_id): book =
Books.query.filter_by(id=book_id,
user_id=current_user.id).first() if not book:
return jsonify({'message': 'book does not exist'})
db.session.delete(book) db.session.commit()
return jsonify({'message': 'Book deleted'})
if __name__ == '__main__':
app.run(debug=True}
Finally, we will create the last route to delete a
specific book. We will create a view responsible
for handling requests made to delete an existing
record in the Books table. It will verify and
delete the given record from the DB, if exists.
The below-mentioned code can be implemented
after the route allows the user to retrieve a list
of books.
@app.route('/books/<book_id>',
methods=['DELETE'])
@token_required
def delete_book(current_user,
book_id): book =
Books.query.filter_by(id=book_id,
user_id=current_user.id).first() if not book:
return jsonify({'message': 'book does not exist'})
db.session.delete(book) db.session.commit()
return jsonify({'message': 'Book deleted'})
if __name__ == '__main__':
app.run(debug=True}
Now run the app.py file by using the following
command inside the virtual environment in the
appropriate directory.
python app.py
If the above command does not work, here’s an
alternative command.
python3 app.py
You can find the entire source code here – Flask
JWT Authentication Example.
Conclusion
So, this was about how to implement Flask JWT
Authentication. I hope the purpose of landing
on this tutorial has been served the way you
expected. If you are interested in learning more
about Python, please visit Python Tutorials and
play around with the code. If you are looking for
assistance for token-based authentication with
Flask, then connect with us today to hire
Python developers from us to secure a Flask
REST API with JSON web token.
Thank You
www.bacancytechnology.com

More Related Content

What's hot

Spring Security
Spring SecuritySpring Security
Spring Security
Knoldus Inc.
 
Sql Antipatterns Strike Back
Sql Antipatterns Strike BackSql Antipatterns Strike Back
Sql Antipatterns Strike Back
Karwin Software Solutions LLC
 
Solid NodeJS with TypeScript, Jest & NestJS
Solid NodeJS with TypeScript, Jest & NestJSSolid NodeJS with TypeScript, Jest & NestJS
Solid NodeJS with TypeScript, Jest & NestJS
Rafael Casuso Romate
 
Spring Framework - Data Access
Spring Framework - Data AccessSpring Framework - Data Access
Spring Framework - Data Access
Dzmitry Naskou
 
Spring Framework Petclinic sample application
Spring Framework Petclinic sample applicationSpring Framework Petclinic sample application
Spring Framework Petclinic sample application
Antoine Rey
 
A Java Microservices Spring Boot and Docker case study.
A Java Microservices Spring Boot and Docker case study.A Java Microservices Spring Boot and Docker case study.
A Java Microservices Spring Boot and Docker case study.
Subramanyam Vemala
 
Content Storage With Apache Jackrabbit
Content Storage With Apache JackrabbitContent Storage With Apache Jackrabbit
Content Storage With Apache JackrabbitJukka Zitting
 
Node.js and the MySQL Document Store
Node.js and the MySQL Document StoreNode.js and the MySQL Document Store
Node.js and the MySQL Document Store
Rui Quelhas
 
Microservices Design Patterns | Edureka
Microservices Design Patterns | EdurekaMicroservices Design Patterns | Edureka
Microservices Design Patterns | Edureka
Edureka!
 
Spring data presentation
Spring data presentationSpring data presentation
Spring data presentation
Oleksii Usyk
 
React Hooks
React HooksReact Hooks
React Hooks
Joao Marins
 
Spring Boot
Spring BootSpring Boot
Spring Boot
Pei-Tang Huang
 
Modern Java web applications with Spring Boot and Thymeleaf
Modern Java web applications with Spring Boot and ThymeleafModern Java web applications with Spring Boot and Thymeleaf
Modern Java web applications with Spring Boot and Thymeleaf
LAY Leangsros
 
I got 99 problems, but ReST ain't one
I got 99 problems, but ReST ain't oneI got 99 problems, but ReST ain't one
I got 99 problems, but ReST ain't one
Adrian Cole
 
XSS Magic tricks
XSS Magic tricksXSS Magic tricks
XSS Magic tricks
GarethHeyes
 
Spring Security 5
Spring Security 5Spring Security 5
Spring Security 5
Jesus Perez Franco
 
Spring data jpa
Spring data jpaSpring data jpa
Spring data jpa
Jeevesh Pandey
 
Dependency injection in Java, from naive to functional
Dependency injection in Java, from naive to functionalDependency injection in Java, from naive to functional
Dependency injection in Java, from naive to functional
Marian Wamsiedel
 
Invoke-Obfuscation nullcon 2017
Invoke-Obfuscation nullcon 2017Invoke-Obfuscation nullcon 2017
Invoke-Obfuscation nullcon 2017
Daniel Bohannon
 
SQL Injection: complete walkthrough (not only) for PHP developers
SQL Injection: complete walkthrough (not only) for PHP developersSQL Injection: complete walkthrough (not only) for PHP developers
SQL Injection: complete walkthrough (not only) for PHP developers
Krzysztof Kotowicz
 

What's hot (20)

Spring Security
Spring SecuritySpring Security
Spring Security
 
Sql Antipatterns Strike Back
Sql Antipatterns Strike BackSql Antipatterns Strike Back
Sql Antipatterns Strike Back
 
Solid NodeJS with TypeScript, Jest & NestJS
Solid NodeJS with TypeScript, Jest & NestJSSolid NodeJS with TypeScript, Jest & NestJS
Solid NodeJS with TypeScript, Jest & NestJS
 
Spring Framework - Data Access
Spring Framework - Data AccessSpring Framework - Data Access
Spring Framework - Data Access
 
Spring Framework Petclinic sample application
Spring Framework Petclinic sample applicationSpring Framework Petclinic sample application
Spring Framework Petclinic sample application
 
A Java Microservices Spring Boot and Docker case study.
A Java Microservices Spring Boot and Docker case study.A Java Microservices Spring Boot and Docker case study.
A Java Microservices Spring Boot and Docker case study.
 
Content Storage With Apache Jackrabbit
Content Storage With Apache JackrabbitContent Storage With Apache Jackrabbit
Content Storage With Apache Jackrabbit
 
Node.js and the MySQL Document Store
Node.js and the MySQL Document StoreNode.js and the MySQL Document Store
Node.js and the MySQL Document Store
 
Microservices Design Patterns | Edureka
Microservices Design Patterns | EdurekaMicroservices Design Patterns | Edureka
Microservices Design Patterns | Edureka
 
Spring data presentation
Spring data presentationSpring data presentation
Spring data presentation
 
React Hooks
React HooksReact Hooks
React Hooks
 
Spring Boot
Spring BootSpring Boot
Spring Boot
 
Modern Java web applications with Spring Boot and Thymeleaf
Modern Java web applications with Spring Boot and ThymeleafModern Java web applications with Spring Boot and Thymeleaf
Modern Java web applications with Spring Boot and Thymeleaf
 
I got 99 problems, but ReST ain't one
I got 99 problems, but ReST ain't oneI got 99 problems, but ReST ain't one
I got 99 problems, but ReST ain't one
 
XSS Magic tricks
XSS Magic tricksXSS Magic tricks
XSS Magic tricks
 
Spring Security 5
Spring Security 5Spring Security 5
Spring Security 5
 
Spring data jpa
Spring data jpaSpring data jpa
Spring data jpa
 
Dependency injection in Java, from naive to functional
Dependency injection in Java, from naive to functionalDependency injection in Java, from naive to functional
Dependency injection in Java, from naive to functional
 
Invoke-Obfuscation nullcon 2017
Invoke-Obfuscation nullcon 2017Invoke-Obfuscation nullcon 2017
Invoke-Obfuscation nullcon 2017
 
SQL Injection: complete walkthrough (not only) for PHP developers
SQL Injection: complete walkthrough (not only) for PHP developersSQL Injection: complete walkthrough (not only) for PHP developers
SQL Injection: complete walkthrough (not only) for PHP developers
 

Similar to Flask jwt authentication tutorial

IPaste SDK v.1.0
IPaste SDK v.1.0IPaste SDK v.1.0
IPaste SDK v.1.0
xrebyc
 
OpenWhisk by Example - Auto Retweeting Example in Python
OpenWhisk by Example - Auto Retweeting Example in PythonOpenWhisk by Example - Auto Retweeting Example in Python
OpenWhisk by Example - Auto Retweeting Example in Python
CodeOps Technologies LLP
 
Setting up the hyperledger composer in ubuntu
Setting up the hyperledger composer in ubuntuSetting up the hyperledger composer in ubuntu
Setting up the hyperledger composer in ubuntu
kesavan N B
 
Build restful ap is with python and flask
Build restful ap is with python and flaskBuild restful ap is with python and flask
Build restful ap is with python and flask
Jeetendra singh
 
Tomcat + other things
Tomcat + other thingsTomcat + other things
Tomcat + other things
Aravindharamanan S
 
LvivPy - Flask in details
LvivPy - Flask in detailsLvivPy - Flask in details
LvivPy - Flask in details
Max Klymyshyn
 
Flask
FlaskFlask
Readme
ReadmeReadme
Readme
rec2006
 
Exploit Frameworks
Exploit FrameworksExploit Frameworks
Exploit Frameworksphanleson
 
Python3 (boto3) for aws
Python3 (boto3) for awsPython3 (boto3) for aws
Python3 (boto3) for aws
Sanjeev Kumar Jaiswal
 
Integrating dialog flow (api.ai) into qiscus sdk chat application
Integrating dialog flow (api.ai) into qiscus sdk chat applicationIntegrating dialog flow (api.ai) into qiscus sdk chat application
Integrating dialog flow (api.ai) into qiscus sdk chat application
Erick Ranes Akbar Mawuntu
 
Jump into Squeak - Integrate Squeak projects with Docker & Github
Jump into Squeak - Integrate Squeak projects with Docker & GithubJump into Squeak - Integrate Squeak projects with Docker & Github
Jump into Squeak - Integrate Squeak projects with Docker & Github
hubx
 
PVS-Studio: analyzing pull requests in Azure DevOps using self-hosted agents
PVS-Studio: analyzing pull requests in Azure DevOps using self-hosted agentsPVS-Studio: analyzing pull requests in Azure DevOps using self-hosted agents
PVS-Studio: analyzing pull requests in Azure DevOps using self-hosted agents
Andrey Karpov
 
Learn you some Ansible for great good!
Learn you some Ansible for great good!Learn you some Ansible for great good!
Learn you some Ansible for great good!
David Lapsley
 
The Mobile ToolChain with Fastlane - Code Red Talk at RedBlackTree
The Mobile ToolChain with Fastlane - Code Red Talk at RedBlackTreeThe Mobile ToolChain with Fastlane - Code Red Talk at RedBlackTree
The Mobile ToolChain with Fastlane - Code Red Talk at RedBlackTree
RedBlackTree
 
2600 av evasion_deuce
2600 av evasion_deuce2600 av evasion_deuce
2600 av evasion_deuceDb Cooper
 
3 Ways to Get Started with a React App in 2024.pdf
3 Ways to Get Started with a React App in 2024.pdf3 Ways to Get Started with a React App in 2024.pdf
3 Ways to Get Started with a React App in 2024.pdf
BOSC Tech Labs
 
Riga Dev Day - Automated Android Continuous Integration
Riga Dev Day - Automated Android Continuous IntegrationRiga Dev Day - Automated Android Continuous Integration
Riga Dev Day - Automated Android Continuous Integration
Nicolas Fränkel
 
sfdx continuous Integration with Jenkins on aws (Part I)
sfdx continuous Integration with Jenkins on aws (Part I)sfdx continuous Integration with Jenkins on aws (Part I)
sfdx continuous Integration with Jenkins on aws (Part I)
Jérémy Vial
 
OpenERP Technical Memento
OpenERP Technical MementoOpenERP Technical Memento
OpenERP Technical MementoOdoo
 

Similar to Flask jwt authentication tutorial (20)

IPaste SDK v.1.0
IPaste SDK v.1.0IPaste SDK v.1.0
IPaste SDK v.1.0
 
OpenWhisk by Example - Auto Retweeting Example in Python
OpenWhisk by Example - Auto Retweeting Example in PythonOpenWhisk by Example - Auto Retweeting Example in Python
OpenWhisk by Example - Auto Retweeting Example in Python
 
Setting up the hyperledger composer in ubuntu
Setting up the hyperledger composer in ubuntuSetting up the hyperledger composer in ubuntu
Setting up the hyperledger composer in ubuntu
 
Build restful ap is with python and flask
Build restful ap is with python and flaskBuild restful ap is with python and flask
Build restful ap is with python and flask
 
Tomcat + other things
Tomcat + other thingsTomcat + other things
Tomcat + other things
 
LvivPy - Flask in details
LvivPy - Flask in detailsLvivPy - Flask in details
LvivPy - Flask in details
 
Flask
FlaskFlask
Flask
 
Readme
ReadmeReadme
Readme
 
Exploit Frameworks
Exploit FrameworksExploit Frameworks
Exploit Frameworks
 
Python3 (boto3) for aws
Python3 (boto3) for awsPython3 (boto3) for aws
Python3 (boto3) for aws
 
Integrating dialog flow (api.ai) into qiscus sdk chat application
Integrating dialog flow (api.ai) into qiscus sdk chat applicationIntegrating dialog flow (api.ai) into qiscus sdk chat application
Integrating dialog flow (api.ai) into qiscus sdk chat application
 
Jump into Squeak - Integrate Squeak projects with Docker & Github
Jump into Squeak - Integrate Squeak projects with Docker & GithubJump into Squeak - Integrate Squeak projects with Docker & Github
Jump into Squeak - Integrate Squeak projects with Docker & Github
 
PVS-Studio: analyzing pull requests in Azure DevOps using self-hosted agents
PVS-Studio: analyzing pull requests in Azure DevOps using self-hosted agentsPVS-Studio: analyzing pull requests in Azure DevOps using self-hosted agents
PVS-Studio: analyzing pull requests in Azure DevOps using self-hosted agents
 
Learn you some Ansible for great good!
Learn you some Ansible for great good!Learn you some Ansible for great good!
Learn you some Ansible for great good!
 
The Mobile ToolChain with Fastlane - Code Red Talk at RedBlackTree
The Mobile ToolChain with Fastlane - Code Red Talk at RedBlackTreeThe Mobile ToolChain with Fastlane - Code Red Talk at RedBlackTree
The Mobile ToolChain with Fastlane - Code Red Talk at RedBlackTree
 
2600 av evasion_deuce
2600 av evasion_deuce2600 av evasion_deuce
2600 av evasion_deuce
 
3 Ways to Get Started with a React App in 2024.pdf
3 Ways to Get Started with a React App in 2024.pdf3 Ways to Get Started with a React App in 2024.pdf
3 Ways to Get Started with a React App in 2024.pdf
 
Riga Dev Day - Automated Android Continuous Integration
Riga Dev Day - Automated Android Continuous IntegrationRiga Dev Day - Automated Android Continuous Integration
Riga Dev Day - Automated Android Continuous Integration
 
sfdx continuous Integration with Jenkins on aws (Part I)
sfdx continuous Integration with Jenkins on aws (Part I)sfdx continuous Integration with Jenkins on aws (Part I)
sfdx continuous Integration with Jenkins on aws (Part I)
 
OpenERP Technical Memento
OpenERP Technical MementoOpenERP Technical Memento
OpenERP Technical Memento
 

More from Katy Slemon

React Alternatives Frameworks- Lightweight Javascript Libraries.pdf
React Alternatives Frameworks- Lightweight Javascript Libraries.pdfReact Alternatives Frameworks- Lightweight Javascript Libraries.pdf
React Alternatives Frameworks- Lightweight Javascript Libraries.pdf
Katy Slemon
 
Data Science Use Cases in Retail & Healthcare Industries.pdf
Data Science Use Cases in Retail & Healthcare Industries.pdfData Science Use Cases in Retail & Healthcare Industries.pdf
Data Science Use Cases in Retail & Healthcare Industries.pdf
Katy Slemon
 
How Much Does It Cost To Hire Golang Developer.pdf
How Much Does It Cost To Hire Golang Developer.pdfHow Much Does It Cost To Hire Golang Developer.pdf
How Much Does It Cost To Hire Golang Developer.pdf
Katy Slemon
 
What’s New in Flutter 3.pdf
What’s New in Flutter 3.pdfWhat’s New in Flutter 3.pdf
What’s New in Flutter 3.pdf
Katy Slemon
 
Why Use Ruby On Rails.pdf
Why Use Ruby On Rails.pdfWhy Use Ruby On Rails.pdf
Why Use Ruby On Rails.pdf
Katy Slemon
 
How Much Does It Cost To Hire Full Stack Developer In 2022.pdf
How Much Does It Cost To Hire Full Stack Developer In 2022.pdfHow Much Does It Cost To Hire Full Stack Developer In 2022.pdf
How Much Does It Cost To Hire Full Stack Developer In 2022.pdf
Katy Slemon
 
How to Implement Middleware Pipeline in VueJS.pdf
How to Implement Middleware Pipeline in VueJS.pdfHow to Implement Middleware Pipeline in VueJS.pdf
How to Implement Middleware Pipeline in VueJS.pdf
Katy Slemon
 
How to Build Laravel Package Using Composer.pdf
How to Build Laravel Package Using Composer.pdfHow to Build Laravel Package Using Composer.pdf
How to Build Laravel Package Using Composer.pdf
Katy Slemon
 
Sure Shot Ways To Improve And Scale Your Node js Performance.pdf
Sure Shot Ways To Improve And Scale Your Node js Performance.pdfSure Shot Ways To Improve And Scale Your Node js Performance.pdf
Sure Shot Ways To Improve And Scale Your Node js Performance.pdf
Katy Slemon
 
How to Develop Slack Bot Using Golang.pdf
How to Develop Slack Bot Using Golang.pdfHow to Develop Slack Bot Using Golang.pdf
How to Develop Slack Bot Using Golang.pdf
Katy Slemon
 
IoT Based Battery Management System in Electric Vehicles.pdf
IoT Based Battery Management System in Electric Vehicles.pdfIoT Based Battery Management System in Electric Vehicles.pdf
IoT Based Battery Management System in Electric Vehicles.pdf
Katy Slemon
 
Understanding Flexbox Layout in React Native.pdf
Understanding Flexbox Layout in React Native.pdfUnderstanding Flexbox Layout in React Native.pdf
Understanding Flexbox Layout in React Native.pdf
Katy Slemon
 
The Ultimate Guide to Laravel Performance Optimization in 2022.pdf
The Ultimate Guide to Laravel Performance Optimization in 2022.pdfThe Ultimate Guide to Laravel Performance Optimization in 2022.pdf
The Ultimate Guide to Laravel Performance Optimization in 2022.pdf
Katy Slemon
 
New Features in iOS 15 and Swift 5.5.pdf
New Features in iOS 15 and Swift 5.5.pdfNew Features in iOS 15 and Swift 5.5.pdf
New Features in iOS 15 and Swift 5.5.pdf
Katy Slemon
 
How to Hire & Manage Dedicated Team For Your Next Product Development.pdf
How to Hire & Manage Dedicated Team For Your Next Product Development.pdfHow to Hire & Manage Dedicated Team For Your Next Product Development.pdf
How to Hire & Manage Dedicated Team For Your Next Product Development.pdf
Katy Slemon
 
Choose the Right Battery Management System for Lithium Ion Batteries.pdf
Choose the Right Battery Management System for Lithium Ion Batteries.pdfChoose the Right Battery Management System for Lithium Ion Batteries.pdf
Choose the Right Battery Management System for Lithium Ion Batteries.pdf
Katy Slemon
 
Flutter Performance Tuning Best Practices From the Pros.pdf
Flutter Performance Tuning Best Practices From the Pros.pdfFlutter Performance Tuning Best Practices From the Pros.pdf
Flutter Performance Tuning Best Practices From the Pros.pdf
Katy Slemon
 
Angular Universal How to Build Angular SEO Friendly App.pdf
Angular Universal How to Build Angular SEO Friendly App.pdfAngular Universal How to Build Angular SEO Friendly App.pdf
Angular Universal How to Build Angular SEO Friendly App.pdf
Katy Slemon
 
How to Set Up and Send Mails Using SendGrid in NodeJs App.pdf
How to Set Up and Send Mails Using SendGrid in NodeJs App.pdfHow to Set Up and Send Mails Using SendGrid in NodeJs App.pdf
How to Set Up and Send Mails Using SendGrid in NodeJs App.pdf
Katy Slemon
 
Ruby On Rails Performance Tuning Guide.pdf
Ruby On Rails Performance Tuning Guide.pdfRuby On Rails Performance Tuning Guide.pdf
Ruby On Rails Performance Tuning Guide.pdf
Katy Slemon
 

More from Katy Slemon (20)

React Alternatives Frameworks- Lightweight Javascript Libraries.pdf
React Alternatives Frameworks- Lightweight Javascript Libraries.pdfReact Alternatives Frameworks- Lightweight Javascript Libraries.pdf
React Alternatives Frameworks- Lightweight Javascript Libraries.pdf
 
Data Science Use Cases in Retail & Healthcare Industries.pdf
Data Science Use Cases in Retail & Healthcare Industries.pdfData Science Use Cases in Retail & Healthcare Industries.pdf
Data Science Use Cases in Retail & Healthcare Industries.pdf
 
How Much Does It Cost To Hire Golang Developer.pdf
How Much Does It Cost To Hire Golang Developer.pdfHow Much Does It Cost To Hire Golang Developer.pdf
How Much Does It Cost To Hire Golang Developer.pdf
 
What’s New in Flutter 3.pdf
What’s New in Flutter 3.pdfWhat’s New in Flutter 3.pdf
What’s New in Flutter 3.pdf
 
Why Use Ruby On Rails.pdf
Why Use Ruby On Rails.pdfWhy Use Ruby On Rails.pdf
Why Use Ruby On Rails.pdf
 
How Much Does It Cost To Hire Full Stack Developer In 2022.pdf
How Much Does It Cost To Hire Full Stack Developer In 2022.pdfHow Much Does It Cost To Hire Full Stack Developer In 2022.pdf
How Much Does It Cost To Hire Full Stack Developer In 2022.pdf
 
How to Implement Middleware Pipeline in VueJS.pdf
How to Implement Middleware Pipeline in VueJS.pdfHow to Implement Middleware Pipeline in VueJS.pdf
How to Implement Middleware Pipeline in VueJS.pdf
 
How to Build Laravel Package Using Composer.pdf
How to Build Laravel Package Using Composer.pdfHow to Build Laravel Package Using Composer.pdf
How to Build Laravel Package Using Composer.pdf
 
Sure Shot Ways To Improve And Scale Your Node js Performance.pdf
Sure Shot Ways To Improve And Scale Your Node js Performance.pdfSure Shot Ways To Improve And Scale Your Node js Performance.pdf
Sure Shot Ways To Improve And Scale Your Node js Performance.pdf
 
How to Develop Slack Bot Using Golang.pdf
How to Develop Slack Bot Using Golang.pdfHow to Develop Slack Bot Using Golang.pdf
How to Develop Slack Bot Using Golang.pdf
 
IoT Based Battery Management System in Electric Vehicles.pdf
IoT Based Battery Management System in Electric Vehicles.pdfIoT Based Battery Management System in Electric Vehicles.pdf
IoT Based Battery Management System in Electric Vehicles.pdf
 
Understanding Flexbox Layout in React Native.pdf
Understanding Flexbox Layout in React Native.pdfUnderstanding Flexbox Layout in React Native.pdf
Understanding Flexbox Layout in React Native.pdf
 
The Ultimate Guide to Laravel Performance Optimization in 2022.pdf
The Ultimate Guide to Laravel Performance Optimization in 2022.pdfThe Ultimate Guide to Laravel Performance Optimization in 2022.pdf
The Ultimate Guide to Laravel Performance Optimization in 2022.pdf
 
New Features in iOS 15 and Swift 5.5.pdf
New Features in iOS 15 and Swift 5.5.pdfNew Features in iOS 15 and Swift 5.5.pdf
New Features in iOS 15 and Swift 5.5.pdf
 
How to Hire & Manage Dedicated Team For Your Next Product Development.pdf
How to Hire & Manage Dedicated Team For Your Next Product Development.pdfHow to Hire & Manage Dedicated Team For Your Next Product Development.pdf
How to Hire & Manage Dedicated Team For Your Next Product Development.pdf
 
Choose the Right Battery Management System for Lithium Ion Batteries.pdf
Choose the Right Battery Management System for Lithium Ion Batteries.pdfChoose the Right Battery Management System for Lithium Ion Batteries.pdf
Choose the Right Battery Management System for Lithium Ion Batteries.pdf
 
Flutter Performance Tuning Best Practices From the Pros.pdf
Flutter Performance Tuning Best Practices From the Pros.pdfFlutter Performance Tuning Best Practices From the Pros.pdf
Flutter Performance Tuning Best Practices From the Pros.pdf
 
Angular Universal How to Build Angular SEO Friendly App.pdf
Angular Universal How to Build Angular SEO Friendly App.pdfAngular Universal How to Build Angular SEO Friendly App.pdf
Angular Universal How to Build Angular SEO Friendly App.pdf
 
How to Set Up and Send Mails Using SendGrid in NodeJs App.pdf
How to Set Up and Send Mails Using SendGrid in NodeJs App.pdfHow to Set Up and Send Mails Using SendGrid in NodeJs App.pdf
How to Set Up and Send Mails Using SendGrid in NodeJs App.pdf
 
Ruby On Rails Performance Tuning Guide.pdf
Ruby On Rails Performance Tuning Guide.pdfRuby On Rails Performance Tuning Guide.pdf
Ruby On Rails Performance Tuning Guide.pdf
 

Recently uploaded

Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered QualitySoftware Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Inflectra
 
Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...
Product School
 
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdfFIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance
 
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Ramesh Iyer
 
Generating a custom Ruby SDK for your web service or Rails API using Smithy
Generating a custom Ruby SDK for your web service or Rails API using SmithyGenerating a custom Ruby SDK for your web service or Rails API using Smithy
Generating a custom Ruby SDK for your web service or Rails API using Smithy
g2nightmarescribd
 
Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........
Alison B. Lowndes
 
To Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMsTo Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMs
Paul Groth
 
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
BookNet Canada
 
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
Product School
 
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Albert Hoitingh
 
Elevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object CalisthenicsElevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object Calisthenics
Dorra BARTAGUIZ
 
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
Product School
 
DevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA ConnectDevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA Connect
Kari Kakkonen
 
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
UiPathCommunity
 
UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3
DianaGray10
 
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
James Anderson
 
Leading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdfLeading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdf
OnBoard
 
Accelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish CachingAccelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish Caching
Thijs Feryn
 
Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...
Product School
 
GraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge GraphGraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge Graph
Guy Korland
 

Recently uploaded (20)

Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered QualitySoftware Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
 
Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...
 
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdfFIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
 
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
 
Generating a custom Ruby SDK for your web service or Rails API using Smithy
Generating a custom Ruby SDK for your web service or Rails API using SmithyGenerating a custom Ruby SDK for your web service or Rails API using Smithy
Generating a custom Ruby SDK for your web service or Rails API using Smithy
 
Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........
 
To Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMsTo Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMs
 
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
 
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
 
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
 
Elevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object CalisthenicsElevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object Calisthenics
 
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
 
DevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA ConnectDevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA Connect
 
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
 
UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3
 
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
 
Leading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdfLeading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdf
 
Accelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish CachingAccelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish Caching
 
Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...
 
GraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge GraphGraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge Graph
 

Flask jwt authentication tutorial

  • 2. In the Flask JWT Authentication tutorial, we will build a demo application together; learn about the Flask framework, REST APIs, and Auth Token Authentication. If this is your first time implementing token authentication ib Flask, don’t worry! After going through this tutorial, your doubts would be solved and you won’t be a beginner anymore. For simplifying the tutorial, I have classified it into various sections.
  • 3. CONTENTS 1. What are JSON Web Tokens? 2. What is Flask Framework? 3. Goal of Flask JWT Authentication Tutorial 4. Step-by-step Tutorial to Implement Flask JWT Authentication 5. Conclusion
  • 5. Serialized- This type is used when you’re transferring information to the network via every request and response. It contains a payload, header, and signature. JSON Web Tokens (JWT) is a secure and compact way to transmit data between two parties with the help of JSON objects. JSON web token consists of three parts- Payload Header Signature JSON uses two different structure types for transmitting data.
  • 6. Deserialized- This type is used when you’re reading/writing information to the token. It contains a payload and header.
  • 8. Flask is a python based micro-framework used to build rest API. A “micro-framework” neither implies that your entire web app has to fit into a single Python code file nor Flask lacks functionality. The core idea of the Flask framework is to keep things simple but extensible. It allows developers to add custom extensions for database integration, authentication, session management, and all the other backend systems based on preferences.
  • 10. Before knowing how to implement Flask JWT Authentication, let’s see the video and know what we will build. Watch Video
  • 12. Ubuntu 20.04 OS Postman Python 3.8+ Let’s start the implementation of the Flask JWT Authentication. Here’s my system setup and Flask JWT example for better understanding: Virtual environment Set Up using virtualenv A virtual environment ensures that none of the packages used in the project conflict with system packages. It is also a good practice to avoid polluting your OS by installing every package directly onto the OS.
  • 13. We will use the virtualenv command for setting up a new virtual environment in our project. We will need pip command to proceed further. If you don’t have pip installed on your system, use the below command for installing pip on your system. sudo apt-get install python3-pip Once you have the pip command installed on your system, run the following command to install virtualenv. pip install virtualenv Now, run the mkdir command to create a new folder/directory for storing the virtual environment. mkdir myflaskproject
  • 14. Change the current working directory to myflaskproject: cd myflaskproject Inside the myflaskproject directory, create a new virtual environment with the help of the virtualenv tool: virtualenv venv After you have successfully created a virtual environment using the irtualenv tool, activate the virtual environment using the following command: Now, it’s time to install the packages we need for this project to build Python REST API authentication token and other necessary packages for this API project such as- Install packages using pip
  • 15. flask pyjwt flask-sqlalchemy datetime uuid An efficient way of doing this is by creating a requirements.txt file and listing all the packages into it. You can also declare the versions of the packages wherever necessary. flask==1.1.2 pyjwt==2.0.0 datetime uuid Flask-SQLAlchemy Now, use this file to install all the listed packages with pip. pip install -r requirements.txt
  • 16. Set up a database Users Books To keep this simple, we will use SQLite for this project. Use the following code to install SQLite. sudo apt-get update sudo apt-get install sqlite3 Create a database named “bookstore” consisting of two tables- Users table will store registered users. We will also keep a check, allowing only the registered users to access the Books table. Books table will store the details and information about books, such as the book’s name, author of the book, publication of the book, and submitted by the registered users.
  • 17. Create the database: sqlite3 bookstore.db Run the below command for checking if you have successfully created the database or not: .databases Create a new file named “app.py” in the myflaskproject directory or run this command in your terminal: touch app.py NOTE- while executing commands in the terminal, make sure you do it inside the virtual environment named “venv” we created earlier.
  • 18. Now, paste the following code inside the python file named app.py: app.py from flask import Flask, jsonify, make_response, request from werkzeug.security import generate_password_hash,check_password_hash from flask_sqlalchemy import SQLAlchemy from functools import wraps import uuid import jwt import datetime Let’s see the purpose of importing the packages mentioned above. Packages from Flask framework
  • 19. request – For keeping track of the associated data at the request level during a request. jsonify – We will need jsonify to receive the output responses in JSON format and request flask_sqlalchemy-This package will help us to integrate SQLAlchemy features into the Flask framework. SQLAlchemy is the Object Relational Mapper & Python SQL toolkit that provides full power and flexibility of SQL to developers. check_password_hash- For checking the user’s password. It compares the password provided by the user with the one stored in the database. ⦿Packages from Flask framework ⦿Package from SQLAlchemy ⦿Package from werkzeug.security
  • 20. The package datetime will help us manipulate date and time as date objects. We need this module because python does not have any data type to support dates. Universal Unique Identifiers create random ID numbers for users. The uuid is a very useful package, especially for such database engines that do not support incremental primary key features. Also, it is better to use multi-character alpha-numeric values as IDs instead of using linearly incremental numeric IDs. ⦿datetime ⦿uuid Now it’s time to configure settings for the Bookstore API inside the app.py file using the below code.
  • 21. app.py app = Flask(__name__) app.config['SECRET_KEY']='004f2af45d3a4e161a7d d2d17fdae47f' app.config['SQLALCHEMY_DATABASE_URI']='sql ite://///home/manthantrivedi/Documents/Bacan cy/bacancy_blogs/flask_auth/myflaskproject/bo okstore.db' app.config['SQLALCHEMY_TRACK_MODIFICATI ONS'] = True db = SQLAlchemy(app) Here, the value assigned to the config variable ‘SECRET KEY’ can be auto-generated using a python library named ‘secrets.’ We can simply run the following code in your terminal to generate this value, as shown below.
  • 22. Now, we will create two models for the Books and Users table. app.py class Users(db.Model): id = db.Column(db.Integer, primary_key=True) public_id = db.Column(db.Integer) name = db.Column(db.String(50)) password = db.Column(db.String(50)) admin = db.Column(db.Boolean)
  • 23. class Books(db.Model): id = db.Column(db.Integer, primary_key=True) user_id = db.Column(db.Integer, db.ForeignKey('users.id'), nullable=False) name = db.Column(db.String(50), unique=True, nullable=False) Author = db.Column(db.String(50), unique=True, nullable=False) Publisher = db.Column(db.String(50), nullable=False) book_prize = db.Column(db.Integer) Moving ahead with Flask-JWT Authentication Tutorial. Use the below code for creating tables for both tables: from app import db db.create_all() Generate Users and Books Tables
  • 24. Now, go to the app.py file and create the other functions required. The “login_user” function will generate tokens to allow only registered users to access and manipulate a set of API operations against the Books table. Simply paste the following code after the database model for both tables.
  • 25. def token_required(f): @wraps(f) : decorator(*args, **kwargs): token = None if 'x-access-tokens' in request.headers: token = request.headers['x-access-tokens'] if not token: return jsonify({'message': 'a valid token is missing'}) try: data = jwt.decode(token, app.config['SECRET_KEY'], algorithms= ["HS256"]) current_user = Users.query.filter_by(public_id=data['public_i d']).first() except: return jsonify({'message': 'token is invalid'}) return f(current_user, *args, **kwargs) return decorator
  • 26. This code is actually a special function. This function will create a custom decorator with the code required to create and validate tokens. Python provides a very amazing feature named function decorators. These function decorators allow very neat features for web development. In Flask, each view is considered as a function, and decorators are used for injecting additional functionality to one or more functions. In this case, the functionality handled by this custom decorator will be to create and validate tokens. In this step, we will generate a route for allowing users to register for the Books API using their name and password. With this route, we will create a view to encrypt the user’s password, store the new user’s details into the database, and return a success message. Creating routes for Users tables
  • 27. Again, inside the app.py file, paste the following code after token_required(f) function: @app.route('/register', methods=['POST']) def signup_user(): data = request.get_json() hashed_password = generate_password_hash(data['password'], method='sha256') new_user = Users(public_id=str(uuid.uuid4()), name=data['name'], password=hashed_password, admin=False) db.session.add(new_user) db.session.commit() return jsonify({'message': 'registered successfully'})
  • 28. Now, generate another route that will allow all the registered users to log in. With the login route, we will create a view to handle the user login feature. When a user logs in, the entered password is matched with the user’s stored password. If the password matches successfully, a random token is generated to access the Bookstore API. For instance, we will keep the expiration time for this random token to be 45 minutes. You can simply update your file with the below- mentioned code beneath the registered route we created in the previous step:
  • 29. @app.route('/login', methods=['POST']) def login_user(): auth = request.authorization if not auth or not auth.username or not auth.password: return make_response('could not verify', 401, {'Authentication': 'login required"'}) user = Users.query.filter_by(name=auth.username).fir st() if check_password_hash(user.password, auth.password): token = jwt.encode({'public_id' : user.public_id, 'exp' : datetime.datetime.utcnow() + datetime.timedelta(minutes=45)}, app.config['SECRET_KEY'], "HS256") return jsonify({'token' : token}) return make_response('could not verify', 401, {'Authentication': '"login required"'}) Create another route in the app.py file to get all the registered users. This route verifies the registered users in the Users table and provides the output in JSON format. Use the below code after the login route.
  • 30. @app.route('/users', methods=['GET']) def get_all_users(): users = Users.query.all() result = [] for user in users: user_data = {} user_data['public_id'] = user.public_id user_data['name'] = user.name user_data['password'] = user.password user_data['admin'] = user.admin result.append(user_data) return jsonify({'users': result}) Let’s create routes for the Books table. These routes will allow users to retrieve all the Books in the database and delete them. We will also implement a mandatory check to verify the users having valid tokens can only perform any API requests. Define a route for all the registered users to create a new book. The following code creates a route to meet this requirement: Creating routes for Books tables
  • 31. @app.route('/book', methods=['POST']) @token_required def create_book(current_user): data = request.get_json() new_books = Books(name=data['name'], Author=data['Author'], Publisher=data['Publisher'], book_prize=data['book_prize'], user_id=current_user.id) db.session.add(new_books) db.session.commit() return jsonify({'message' : 'new books created'}) Now, create a route to allow a logged in user with valid token to get all the books in the Books table as shown below:
  • 32. @app.route('/books', methods=['GET']) @token_required def get_books(current_user): books = Books.query.filter_by(user_id=current_user.id) .all() output = [] for book in books: book_data = {} book_data['id'] = book.id book_data['name'] = book.name book_data['Author'] = book.Author book_data['Publisher'] = book.Publisher book_data['book_prize'] = book.book_prize output.append(book_data) return jsonify({'list_of_books' : output}
  • 33. Finally, we will create the last route to delete a specific book. We will create a view responsible for handling requests made to delete an existing record in the Books table. It will verify and delete the given record from the DB, if exists. The below-mentioned code can be implemented after the route allows the user to retrieve a list of books. @app.route('/books/<book_id>', methods=['DELETE']) @token_required def delete_book(current_user, book_id): book = Books.query.filter_by(id=book_id, user_id=current_user.id).first() if not book: return jsonify({'message': 'book does not exist'}) db.session.delete(book) db.session.commit() return jsonify({'message': 'Book deleted'}) if __name__ == '__main__': app.run(debug=True}
  • 34. Finally, we will create the last route to delete a specific book. We will create a view responsible for handling requests made to delete an existing record in the Books table. It will verify and delete the given record from the DB, if exists. The below-mentioned code can be implemented after the route allows the user to retrieve a list of books. @app.route('/books/<book_id>', methods=['DELETE']) @token_required def delete_book(current_user, book_id): book = Books.query.filter_by(id=book_id, user_id=current_user.id).first() if not book: return jsonify({'message': 'book does not exist'}) db.session.delete(book) db.session.commit() return jsonify({'message': 'Book deleted'}) if __name__ == '__main__': app.run(debug=True}
  • 35. Now run the app.py file by using the following command inside the virtual environment in the appropriate directory. python app.py If the above command does not work, here’s an alternative command. python3 app.py You can find the entire source code here – Flask JWT Authentication Example.
  • 37. So, this was about how to implement Flask JWT Authentication. I hope the purpose of landing on this tutorial has been served the way you expected. If you are interested in learning more about Python, please visit Python Tutorials and play around with the code. If you are looking for assistance for token-based authentication with Flask, then connect with us today to hire Python developers from us to secure a Flask REST API with JSON web token.