Super simple JSON Web Tokens for Flask
Project description
Flask-EasyJWT
Flask-EasyJWT provides a simple interface to creating and verifying JSON Web Tokens (JWTs) in Python. It allows you to once define the claims of the JWT, and to then create and accept tokens with these claims without having to check if all the required data is given or if the token actually is the one you expect.
Flask-EasyJWT is a simple wrapper around EasyJWT for easy usage in Flask applications. It provides configuration options via Flask's application configuration for common settings of all tokens created in a web application. For detailed information on how to use EasyJWT, see its documentation.
from flask_easyjwt import FlaskEasyJWT
from flask import Flask
# Define the claims of your token.
class MySuperSimpleJWT(FlaskEasyJWT):
def __init__(self, key):
super().__init__(key)
# Define a claim `name`.
self.name = None
# Define the default configuration options for FlaskEasyJWT
# in the configuration of your Flask app.
app = Flask(__name__)
app.config.from_mapping(
# The default key for encoding and decoding tokens.
EASYJWT_KEY='Super secret key',
# Tokens will be valid for 15 minutes after creation by default.
EASYJWT_TOKEN_VALIDITY=15 * 60
)
@app.route('/token/<name>')
def get_token(name):
""" This view returns a token with the given name as its value. """
token_object = MySuperSimpleJWT()
token_object.name = name
return token_object.create()
@app.route('/verify/<token>')
def verify_token(token):
""" This view verifies the given token and returns the contained name. """
verified_token_object = MySuperSimpleJWT.verify(token)
return verified_token_object.name
Features
- Integrates EasyJWT into Flask for easy configuration of default options for creating and verifying JWTs.
- Define the claims of your token once as a class, then use this class to easily create and verify multiple tokens.
- No worries about typos in dictionary keys: the definition of your claim set as a class enables IDEs to find those typos for you.
- Multiple tokens may have the same claims, but different intentions. Flask-EasyJWT will take care of this for you: you can define a token for account validation and one for account deletion, both with the account ID as a claim, and you don't need to worry about accidentally deleting a newly created account instead of validating it, just because someone mixed up the tokens.
- All registered JWT claims are supported:
aud
,exp
,iat
,iss
,jti
,nbf
, andsub
.
For a full list of features, see the features of EasyJWT.
System Requirements & Installation
Flask-EasyJWT requires Python 3.6 or newer.
Flask-EasyJWT is available on PyPI. You can install it using your favorite package manager.
-
PIP:
python -m pip install flask_easyjwt
-
Pipenv:
pipenv install flask_easyjwt
Usage
Flask-EasyJWT is used exactly as EasyJWT. Therefore, this section only describes the
specific features of Flask-EasyJWT and the basic usage. For detailed explanations on how to use EasyJWT (for example,
optional claims, registered claims such as aud
, iat
, and sub
, or verifying third-party tokens), see
its documentation.
Application Setup
You do not need to initialize Flask-EasyJWT with your Flask application. All you have to do (although even this is, strictly speaking, not required), is to specify some default settings for all of your tokens in the configuration of your Flask application. These settings are:
Configuration Key | Description |
---|---|
EASYJWT_KEY |
The key that will be used for encoding and decoding all tokens. If EASYJWT_KEY is not specified, Flask-EasyJWT will fall back to Flask's SECRET_KEY configuration value. |
EASYJWT_TOKEN_VALIDITY |
The validity of each token after its creation. This value can be given as a string (that is parsable to an integer), an integer, or a timedelta object. The former two are interpreted in seconds. |
You can specify these configuration values as any other configuration values in your Flask application, for example, using a mapping in your code:
from datetime import timedelta
from flask import Flask
app = Flask(__name__)
app.config.update(
EASYJWT_KEY='Super secret key',
EASYJWT_TOKEN_VALIDITY=timedelta(minutes=7)
)
In this example, all tokens will (by default) be encoded using the (not so secure) string Super secret key
and will
be valid for seven minutes after they have been created (i.e., after the create()
method has been called on the token
object).
Of course, any other way of specifying the configuration values will work as well (see Flask's documentation).
Token Specification & Usage
Tokens are specified and used exactly as with EasyJWT:
from flask_easyjwt import FlaskEasyJWT
# Define the claims of your token.
class MySuperSimpleJWT(FlaskEasyJWT):
def __init__(self, key):
super().__init__(key)
# Define a claim `name`.
self.name = None
# Assuming we are within a Flask app context.
# Create a token with some values.
token_object = MySuperSimpleJWT()
token_object.name = 'Zaphod Beeblebrox'
token = token_object.create()
# Verify the created token.
verified_token_object = MySuperSimpleJWT.verify(token)
assert verified_token_object.name == 'Zaphod Beeblebrox'
The only difference is that you do not have to pass the key for encoding or decoding the token to the constructor and
verify()
method, respectively (you still can do so if you do not want to use the default key defined in your
application's configuration).
Additionally, if the configuration value EASYJWT_TOKEN_VALIDITY
is set, the token will
be valid for the amount specified in this configuration value after it has been created with create()
. If this
configuration value is not set tokens will not expire. If you explicitly set the expiration date on a token object
this value will always take precedence (if it is not None
):
import datetime
from flask_easyjwt import FlaskEasyJWT
from flask import Flask
# Define the claims of your token.
class MySuperSimpleJWT(FlaskEasyJWT):
def __init__(self, key):
super().__init__(key)
# Define a claim `name`.
self.name = None
# Define the default configuration options for FlaskEasyJWT
# in the configuration of your Flask app.
app = Flask(__name__)
app.config.from_mapping(
EASYJWT_KEY='Super secret key',
EASYJWT_TOKEN_VALIDITY=datetime.timedelta(minutes=7)
)
# Assuming we are within a Flask app context.
token_object = MySuperSimpleJWT()
token_object.name = 'Zaphod Beeblebrox'
# This token will expire in 15 minutes, even though the default token validity is set to 7 minutes.
token_object.expiration_date = datetime.datetime.utcnow() + datetime.timedelta(minutes=15)
Initializing token objects and creating and verifying tokens must be executed within a Flask application context if you want to use the configuration values from the application's configuration.
Acknowledgements
Flask-EasyJWT is just an easy-to-use abstraction layer around José Padilla's PyJWT library that does the actual work of creating and verifying the tokens according to the JWT specification. Without his work, Flask-EasyJWT would not be possible.
License
Flask-EasyJWT is developed by Bastian Meyer <bastian@bastianmeyer.eu> and is licensed under the MIT License. For details, see the attached LICENSE file.
Project details
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
File details
Details for the file flask_easyjwt-0.2.2.tar.gz
.
File metadata
- Download URL: flask_easyjwt-0.2.2.tar.gz
- Upload date:
- Size: 8.1 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/1.13.0 pkginfo/1.5.0.1 requests/2.18.4 setuptools/41.0.1 requests-toolbelt/0.9.1 tqdm/4.31.1 CPython/3.6.9
File hashes
Algorithm | Hash digest | |
---|---|---|
SHA256 | 92358f20983a139dc6874bd86c29ccad53778248fce7d0a8ca0fdcc308628374 |
|
MD5 | 7307b799cefa0803ff811a780efb8caf |
|
BLAKE2b-256 | 21f7dfd4f2153dd25412f00bf5047fb3e3be92a66e0d1e8c1a1f913ae208a2b4 |
File details
Details for the file flask_easyjwt-0.2.2-py3-none-any.whl
.
File metadata
- Download URL: flask_easyjwt-0.2.2-py3-none-any.whl
- Upload date:
- Size: 9.1 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/1.13.0 pkginfo/1.5.0.1 requests/2.18.4 setuptools/41.0.1 requests-toolbelt/0.9.1 tqdm/4.31.1 CPython/3.6.9
File hashes
Algorithm | Hash digest | |
---|---|---|
SHA256 | ced5d8afef91e7b1fc947ba28ce9fdfe59f11ac90b131d1f9b46fdcbd3216ede |
|
MD5 | e6efc2c1f442b5b4ead70a468a8e5537 |
|
BLAKE2b-256 | b425b5edb7628f5d10817b827d396a5dc02a879349e44f784b89a99734555a19 |