Python module for generating and verifying JSON Web Tokens

Overview

python-jwt   Build Status Coverage Status PyPI version

Module for generating and verifying JSON Web Tokens.

  • Note: From version 2.0.1 the namespace has changed from jwt to python_jwt, in order to avoid conflict with PyJWT.
  • Note: Versions 1.0.0 and later fix a vulnerability in JSON Web Token verification so please upgrade if you're using this functionality. The API has changed so you will need to update your application. verify_jwt now requires you to specify which signature algorithms are allowed.
  • Uses jwcrypto to do the heavy lifting.
  • Supports RS256, RS384, RS512, PS256, PS384, PS512, HS256, HS384, HS512, ES256, ES384, ES512, ES256K, EdDSA and none signature algorithms.
  • Unit tests, including tests for interoperability with jose.
  • Supports Python 2,7 and 3.6+. Note: generate_jwt returns the token as a Unicode string, even on Python 2.7.

Example:

import python_jwt as jwt, jwcrypto.jwk as jwk, datetime
key = jwk.JWK.generate(kty='RSA', size=2048)
payload = { 'foo': 'bar', 'wup': 90 };
token = jwt.generate_jwt(payload, key, 'PS256', datetime.timedelta(minutes=5))
header, claims = jwt.verify_jwt(token, key, ['PS256'])
for k in payload: assert claims[k] == payload[k]

The API is described here.

Installation

pip install python_jwt

Another Example

You can read and write keys from and to PEM-format strings:

import python_jwt as jwt, jwcrypto.jwk as jwk, datetime
key = jwk.JWK.generate(kty='RSA', size=2048)
priv_pem = key.export_to_pem(private_key=True, password=None)
pub_pem = key.export_to_pem()
payload = { 'foo': 'bar', 'wup': 90 };
priv_key = jwk.JWK.from_pem(priv_pem)
pub_key = jwk.JWK.from_pem(pub_pem)
token = jwt.generate_jwt(payload, priv_key, 'RS256', datetime.timedelta(minutes=5))
header, claims = jwt.verify_jwt(token, pub_key, ['RS256'])
for k in payload: assert claims[k] == payload[k]

Licence

MIT

Tests

make test

Lint

make lint

Code Coverage

make coverage

coverage.py results are available here.

Coveralls page is here.

Benchmarks

make bench

Here are some results on a laptop with an Intel Core i5-4300M 2.6Ghz CPU and 8Gb RAM running Ubuntu 17.04.

Generate Key user (ns) sys (ns) real (ns)
RSA 103,100,000 200,000 103,341,537
Generate Token user (ns) sys (ns) real (ns)
HS256 220,000 0 226,478
HS384 220,000 0 218,233
HS512 230,000 0 225,823
PS256 1,530,000 10,000 1,536,235
PS384 1,550,000 0 1,549,844
PS512 1,520,000 10,000 1,524,844
RS256 1,520,000 10,000 1,524,565
RS384 1,530,000 0 1,528,074
RS512 1,510,000 0 1,526,089
Load Key user (ns) sys (ns) real (ns)
RSA 210,000 3,000 210,791
Verify Token user (ns) sys (ns) real (ns)
HS256 100,000 0 101,478
HS384 100,000 10,000 103,014
HS512 110,000 0 104,323
PS256 230,000 0 231,058
PS384 240,000 0 237,551
PS512 240,000 0 232,450
RS256 230,000 0 227,737
RS384 230,000 0 230,698
RS512 230,000 0 228,624
Comments
  • Wrong path when not using a virtualenv

    Wrong path when not using a virtualenv

    If I install this package without a virtualenv, my package is in /usr/local/local/lib/python2.7/dist-packages (there is local twice in the path).

    It happened with jwt==0.3.2, python-jwt==0.3.3 and python-jwt==1.0.0

    opened by immortal-tofu 14
  • README: use SVG, remove duplicate RST

    README: use SVG, remove duplicate RST

    Two changes:


    1. Use SVG badges for consistency:

    Before:

    image

    https://github.com/davedoesdev/python-jwt/blob/49d0987a750b08569960d61d71f5137c7657919b/README.md

    After:

    image

    https://github.com/davedoesdev/python-jwt/blob/61b3992112141be83f86283e680d5f314563a03e/README.md


    1. Remove duplicate README.rst

    The good news is the new PyPI (aka Warehouse) now supports Markdown for the description, so we can use README.md without conversion!

    For more info and examples:

    • https://pypi.org/project/markdown-description-example/
    • https://dustingram.com/articles/2018/03/16/markdown-descriptions-on-pypi
    • https://github.com/di/markdown-description-example
    opened by hugovk 9
  • Header Parameter kid not implemented in the context of verifying , even though check optional is false

    Header Parameter kid not implemented in the context of verifying , even though check optional is false

    it seems to be caused by jws , which does check all of them and throw an error

    https://github.com/brianloveswords/python-jws/blob/master/jws/header.py#L52

    opened by allan-simon 8
  • When verifying tokens, use utf-8 encoding by default.

    When verifying tokens, use utf-8 encoding by default.

    Since other jwt libraries generate tokens with utf-8 encoded data by default, python-jwt should be able to decode these without error. Also adds the option to use other encodings if needed.

    opened by benekastah 8
  • Error with

    Error with "pip install python_jwt" - Python 3.4

    I think this is a compatibility problem with Python 3.4 and print function.

    SyntaxError: invalid syntax
    Complete output from command python setup.py egg_info:
    Traceback (most recent call last):
    

    File "", line 17, in

    File "/Users/christianbarra/Dev/jwt/build/python-jwt/setup.py", line 1, in

    import dist.bentomaker
    

    File "/Users/christianbarra/Dev/jwt/build/python-jwt/dist/bentomaker.py", line 22

    print "Error: %s" % m
    
                    ^
    

    SyntaxError: invalid syntax

    opened by barrachri 8
  • Error when installing python-jwt with newer pip

    Error when installing python-jwt with newer pip

    Here is the output:

    $ pip install python-jwt Downloading/unpacking python-jwt Downloading python_jwt-0.3.0.tar.gz (445kB): 445kB downloaded Running setup.py egg_info for package python-jwt Requirement already satisfied (use --upgrade to upgrade): jws>=0.1.2 Installing collected packages: python-jwt Running setup.py install for python-jwt usage: -c [global_opts] cmd1 [cmd1_opts] [cmd2 [cmd2_opts] ...] or: -c --help [cmd1 cmd2 ...] or: -c --help-commands or: -c cmd --help

    error: option --compile not recognized
    
    opened by rslinckx 7
  • Install with pip

    Install with pip

    Hi, although I have tried many times the process of installing this package with pip on Linux, it does not work. It always ends with a broken installation and setting up files on ''/usr/local/local/lib/python2.7/dist-packages/'. Here is the verbose output of the pip command(pip -vvv install python_jwt)

    Downloading python_jwt-1.0.0.tar.gz (447kB):
      Downloading from URL https://pypi.python.org/packages/source/p/python_jwt/python_jwt-1.0.0.tar.gz#md5=12a7f8b44a7345f7db6abb348f7d348a (from https://pypi.python.org/simple/python-jwt/)
    ...Downloading python_jwt-1.0.0.tar.gz (447kB): 447kB downloaded
      Running setup.py (path:/tmp/pip_build_root/python-jwt/setup.py) egg_info for package python-jwt
        /usr/lib/python2.7/distutils/dist.py:267: UserWarning: Unknown distribution option: 'summary'
          warnings.warn(msg)
        /usr/lib/python2.7/distutils/dist.py:267: UserWarning: Unknown distribution option: 'home_page'
          warnings.warn(msg)
        running egg_info
        running build
        running config
      Source in /tmp/pip_build_root/python-jwt has version 1.0.0, which satisfies requirement python-jwt
    Requirement already satisfied (use --upgrade to upgrade): jws>=0.1.2 in /usr/local/lib/python2.7/dist-packages (from python-jwt)
    Installing collected packages: python-jwt
      Running setup.py install for python-jwt
        Running command /usr/bin/python -c "import setuptools, tokenize;__file__='/tmp/pip_build_root/python-jwt/setup.py';exec(compile(getattr(tokenize, 'open', open)(__file__).read().replace('\r\n', '\n'), __file__, 'exec'))" install --record /tmp/pip-OC2che-record/install-record.txt --single-version-externally-managed --compile
        /usr/lib/python2.7/distutils/dist.py:267: UserWarning: Unknown distribution option: 'summary'
          warnings.warn(msg)
        /usr/lib/python2.7/distutils/dist.py:267: UserWarning: Unknown distribution option: 'home_page'
          warnings.warn(msg)
        running install
        /tmp/pip_build_root/python-jwt/dist/.bentomaker.py-0.1-07628d92704c3a8f4413b0c74c228d35/bento/distutils/commands/install.py:59: UserWarning: --compile option is ignored.
          warnings.warn("--compile option is ignored.")
        running build
        running config
    Successfully installed python-jwt
    

    Here is the destination directory after the install:

    /usr/local/local/lib/python2.7/dist-packages/python_jwt-1.0.0-py2.7.egg-info
    

    Thanks

    opened by f2hex 6
  • Unable to install released version

    Unable to install released version

    When trying to install last release, it fails:

    Downloading/unpacking python-jwt Downloading python_jwt-0.2.0.tar.gz (445kB): 445kB downloaded Running setup.py egg_info for package python-jwt Downloading/unpacking jws-pss==0.1.0 (from python-jwt) HTTP error 404 while getting http://github.com/davedoesdev/python-jws/tarball/master#egg=jws-pss-0.1.0 Could not install requirement jws-pss==0.1.0 (from python-jwt) because of error HTTP Error 404: Not Found Cleaning up... Could not install requirement jws-pss==0.1.0 (from python-jwt) because of HTTP error HTTP Error 404: Not Found for URL http://github.com/davedoesdev/python-jws/tarball/master#egg=jws-pss-0.1.0

    It seems that either the bundled python-jws is no longer needed but still referenced in the setup.py, or the tarball was accidentally deleted..

    Can you help ?

    opened by rslinckx 6
  • Clashes with pyjwt

    Clashes with pyjwt

    I'm using python-social-auth on the same virtualenv and one of it requirements is https://github.com/jpadilla/pyjwt.

    This causes the import jwt to clash. How can I solve this?

    opened by aericson 4
  • Relax validation a little, don't validate params that aren't there

    Relax validation a little, don't validate params that aren't there

    I came across some issues using this library to validate the JWT's that come back from google OAuth 2.0. Specifically the Google JWT does not contain a typ header or an nbf claim.

    This PR patches it so that only the headers/claims are only checked if they exist.

    opened by alex-hofsteede 4
  • Add ability to specify other headers when generating a token

    Add ability to specify other headers when generating a token

    The RFC7519 spec defines the following headers:

    typ cty alg

    alg and typ are set appropriately by generate_token, however there hasn't been a way to specify cty or any other headers defined by later standards (i.e. by JWE and JWS).

    This adds a new optional parameter to generate_token: other_headers. If specified the key/values will be included with the headers in the token. To avoid misue, if other_headers specifies 'typ' or 'alg' a ValueError will be raised.

    opened by petedmarsh 3
Owner
David Halls
Pub-sub, auth, streams...
David Halls
A Python tool to generate and refresh Amazon access tokens.

amazon_auth A Python tool to generate and refresh Amazon access tokens. Description This tool generates and outputs Amazon access and refresh tokens f

null 15 Nov 21, 2022
A Python library to create and validate authentication tokens

handshake A Python library to create and validate authentication tokens. handshake is used to generate and validate arbitrary authentication tokens th

null 0 Apr 26, 2022
JSON Web Token implementation in Python

PyJWT A Python implementation of RFC 7519. Original implementation was written by @progrium. Sponsor If you want to quickly add secure token-based aut

José Padilla 4.5k Jan 9, 2023
Crie seus tokens de autenticação com o AScrypt.

AScrypt tokens O AScrypt é uma forma de gerar tokens de autenticação para sua aplicação de forma rápida e segura. Todos os tokens que foram, mesmo que

Jaedson Silva 0 Jun 24, 2022
Local server that gives you your OAuth 2.0 tokens needed to interact with the Conta Azul's API

What's this? This is a django project meant to be run locally that gives you your OAuth 2.0 tokens needed to interact with Conta Azul's API Prerequisi

Fábio David Freitas 3 Apr 13, 2022
Creation & manipulation of PyPI tokens

PyPIToken: Manipulate PyPI API tokens PyPIToken is an open-source Python 3.6+ library for generating and manipulating PyPI tokens. PyPI tokens are ver

Joachim Jablon 8 Nov 1, 2022
A JSON Web Token authentication plugin for the Django REST Framework.

Simple JWT Abstract Simple JWT is a JSON Web Token authentication plugin for the Django REST Framework. For full documentation, visit django-rest-fram

Simple JWT 3.3k Jan 1, 2023
JSON Web Token Authentication support for Django REST Framework

REST framework JWT Auth Notice This project is currently unmaintained. Check #484 for more details and suggested alternatives. JSON Web Token Authenti

José Padilla 3.2k Dec 31, 2022
JSON Web Token Authentication support for Django REST Framework

REST framework JWT Auth JSON Web Token Authentication support for Django REST Framework Overview This package provides JSON Web Token Authentication s

Styria Digital Development 178 Jan 2, 2023
A JSON Web Token authentication plugin for the Django REST Framework.

Simple JWT Abstract Simple JWT is a JSON Web Token authentication plugin for the Django REST Framework. For full documentation, visit django-rest-fram

Jazzband 3.2k Dec 29, 2022
A JSON Web Token authentication plugin for the Django REST Framework.

Simple JWT Abstract Simple JWT is a JSON Web Token authentication plugin for the Django REST Framework. For full documentation, visit django-rest-fram

Jazzband 3.2k Dec 28, 2022
Python library for generating a Mastercard API compliant OAuth signature.

oauth1-signer-python Table of Contents Overview Compatibility References Usage Prerequisites Adding the Library to Your Project Importing the Code Loa

null 23 Aug 1, 2022
This app makes it extremely easy to build Django powered SPA's (Single Page App) or Mobile apps exposing all registration and authentication related functionality as CBV's (Class Base View) and REST (JSON)

Welcome to django-rest-auth Repository is unmaintained at the moment (on pause). More info can be found on this issue page: https://github.com/Tivix/d

Tivix 2.4k Jan 3, 2023
A full Rest-API With Oauth2 and JWT for request & response a JSON file Using FastAPI and SQLAlchemy 🔑

Pexon-Rest-API A full Rest-API for request & response a JSON file, Building a Simple WorkFlow that help you to Request a JSON File Format and Handling

Yasser Tahiri 15 Jul 22, 2022
Authentication Module for django rest auth

django-rest-knox Authentication Module for django rest auth Knox provides easy to use authentication for Django REST Framework The aim is to allow for

James McMahon 878 Jan 4, 2023
A secure authentication module to validate user credentials in a Streamlit application.

Streamlit-Authenticator A secure authentication module to validate user credentials in a Streamlit application. Installation Streamlit-Authenticator i

M Khorasani 336 Dec 31, 2022
A module making it easier to manage Discord oAuth with Quart

quart_discord A module making it easier to manage Discord oAuth with Quart Install pip install git+https://github.com/xelA/quart_discord@master How to

null 5 Oct 27, 2022
Simple yet powerful authorization / authentication client library for Python web applications.

Authomatic Authomatic is a framework agnostic library for Python web applications with a minimalistic but powerful interface which simplifies authenti

null 1k Dec 28, 2022
Simple yet powerful authorization / authentication client library for Python web applications.

Authomatic Authomatic is a framework agnostic library for Python web applications with a minimalistic but powerful interface which simplifies authenti

null 962 Feb 4, 2021