Python JSON Web Tokens : Implementation and Tutorial

in #utopian-io6 years ago (edited)

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

jwt.png

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 into python 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 our JWT
    The secret key in our case will be out Flask's SECRET_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

Sort:  

Thanks for the contribution!

Really cool to see you helping out on all kinds of different open source projects!

For future contributions I would recommend combining more "work" into one contribution so you can get a higher score, and in turn a higher reward.


Need help? Write a ticket on https://support.utopian.io/.
Chat with us on Discord.
[utopian-moderator]

sure thanks! :)

Hey @gabrum
Thanks for contributing on Utopian.
We're already looking forward to your next contribution!

Contributing on Utopian
Learn how to contribute on our website or by watching this tutorial on Youtube.

Want to chat? Join us on Discord https://discord.gg/h52nFrV.

Vote for Utopian Witness!