Link to repository : https://github.com/fossasia/badgeyay
Tutorial : Python JSON Web Tokens
What is JWT?
JWT
or JSON Web Tokens
is a compact, URL-safe means of representing claims between two parties. The claim between the parties is often encoded as a payload
onto the JWT
and which is further signed using a SECRET_KEY
.
JWT for Web Developers
The most interesting usage of JWT
is in the field of Web Development.
I have been developing Web Applications for quite a long time now. Recently I was supposed to build an API for an Open Source Project which required me to handle User sessions
. The stack I am using is:
- Python
- Flask Blueprint
- PostgreSQL
- JSON Web Tokens
Installing PyJWT
gabru-md ~ $ pip install pyjwt
Using JWT
Implementing or using JSON web tokens is very easy. All we need to understand is how it works.
A JWT
consists of a payload
which is protected using a SECRET_KEY
. A JWT
has tow main functions
- jwt.encode
- jwt.decode
Let us begin by encoding some stuff into our JSON Web Token
- Fire up your terminal & open Python
gabru-md ~ $ python
- Import
jwt
library intopython shell
import jwt
import datetime
- Create your payload
For our use case we want to generate a JWT for a logged in user into our system. So we will embedd the user details as well as an expiration time into our JSON Web Token.
payload = {
"user": user.username,
"exp": datetime.datetime.utcnow() + datetime.timedelta(seconds=900)
}
- Now we will create a
SECRET_KEY
for ourJWT
The secret key in our case will be out Flask'sSECRET_KEY
. To create one, just follow the steps below.
from flask import Flask
app = Flask(__name__)
app.config['SECRET_KEY'] = 'somesuperrandomsecretkeynoonecancrack'
- Encode your JWT with the
SECRET_KEY
token = jwt.encode(payload, app.config.get('SECRET_KEY')
- View your token generated
print(token.decode('UTF-8'))
Output will be something like
u'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyIjoibWFuaXNoIn0.JX4_nxeJAY8lOSrTiyzU43eKt-qEWXtNhkPwfLWanUY'
Congratulations , Now you have your very own JSON Web Token for your User, which will expire in exactly 900 seconds or 15 minutes :)
I hope to write another blog on Authentication using JWT
very soon. Please let me know If you like this post .
Thank you for reading :)
My Github : github@gabru-md
Link to my PR : here