A JOSE implementation in Python

Overview

python-jose

A JOSE implementation in Python

Build Status Coverage Status Docs

Docs are available on ReadTheDocs.

The JavaScript Object Signing and Encryption (JOSE) technologies - JSON Web Signature (JWS), JSON Web Encryption (JWE), JSON Web Key (JWK), and JSON Web Algorithms (JWA) - collectively can be used to encrypt and/or sign content using a variety of algorithms. While the full set of permutations is extremely large, and might be daunting to some, it is expected that most applications will only use a small set of algorithms to meet their needs.

Installation

$ pip install python-jose[cryptography]

Cryptographic Backends

As of 3.1.0, python-jose implements four different cryptographic backends. The backend must be selected as an extra when installing python-jose. If you do not select a backend, the native-python backend will be installed.

Unless otherwise noted, all backends support all operations.

Due to complexities with setuptools, the native-python backend is always installed, even if you select a different backend on install. We recommend that you remove unnecessary dependencies in production.

  1. cryptography

    • This backend uses pyca/cryptography for all cryptographic operations. This is the recommended backend and is selected over all other backends if any others are present.
    • Installation: pip install python-jose[cryptography]
    • Unused dependencies:
      • rsa
      • ecdsa
      • pyasn1
  2. pycryptodome

    • This backend uses pycryptodome for all cryptographic operations.
    • Installation: pip install python-jose[pycryptodome]
    • Unused dependencies:
      • rsa
  3. native-python

    • This backend uses python-rsa and python-ecdsa for all cryptographic operations. This backend is always installed but any other backend will take precedence if one is installed.
    • Installation: pip install python-jose

    Note

    The native-python backend cannot process certificates.

  4. pycrypto

    • This backend uses pycrypto for all cryptographic operations.
    • Installation: pip install python-jose[pycrypto]
    • Unused dependencies:
      • rsa

    Warning

    The pycrypto project has not been maintained since 2013. This backend is maintained for legacy compatibility purposes only. Do not use this backend unless you cannot use any of the others.

Usage

>>> from jose import jwt
>>> token = jwt.encode({'key': 'value'}, 'secret', algorithm='HS256')
u'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJrZXkiOiJ2YWx1ZSJ9.FG-8UppwHaFp1LgRYQQeS6EDQF7_6-bMFegNucHjmWg'

>>> jwt.decode(token, 'secret', algorithms=['HS256'])
{u'key': u'value'}

Thanks

This library was originally based heavily on the work of the folks over at PyJWT.

Comments
  • Implement PyNaCl backend for Ed25519 keys (part of RFC 8037)

    Implement PyNaCl backend for Ed25519 keys (part of RFC 8037)

    RFC8037 is an extension to JOSE that includes Ed25519 and Ed448 keys.

    This PR adds support for Ed25519 keys in a new nacl backend using the wonderful PyNaCl package, and integrates it into the JWK portion of this project.

    Unfortunately, while Ed448 keys are part of RFC8037, there are no good Python libraries for those keys yet, so support for them was left out. Implementation of that is a good candidate for future work, but will not be considered part of this PR.

    This PR should be good to go (assuming it passes CI tests). 😃

    opened by blag 20
  • Various issues in jwt.decode / jws._get_keys

    Various issues in jwt.decode / jws._get_keys

    I've had a couple issues (figuring out how to use jwt.decode) which stem from the jws._get_keys implementation.

    1. key argument must be iterable- raises exception otherwise
    2. string key argument must not contain 'keys' (ie if a PEM base64 segment or HS secret segment contains keys, it'll break)
    3. key can't be the result of calling jwk.construct (usability issue)
    4. attempting json.loads on anything not a string seems weird
    opened by codertao 16
  • chore: fix cryptography warning

    chore: fix cryptography warning

    Fix a warning emitted by cryptography since a recent release.

    /usr/local/lib/python3.7/site-packages/jose/backends/cryptography_backend.py:18: CryptographyDeprecationWarning: int_from_bytes is deprecated, use int.from_bytes instead
      from cryptography.utils import int_from_bytes, int_to_bytes
    

    Edit: The warning comes from cryptography 3.4 release. Since this release only python 3.6+ is supported. This PR fixes the warning by using int.from_bytes, which is only available since python 3.2. So obviously python 2.7 is not supported anymore cryptography.

    So the solutions for python-jose are:

    1. drop python 2 support completely. This is the right solution IMO, it's 2021 after all.
    2. pin the cryptography dep in setup.py to <3.4 if python 2 is detected and make the imports conditional. Defining the deps a bit more strictly would make sense anyways.
    opened by sbor23 14
  • Replace PyCrypto with cryptography.

    Replace PyCrypto with cryptography.

    I know the cryptodome route is easier, but cryptography is the way to go for the long run because it is supported by the python software foundation. Feel free to give feedback and suggestions!

    opened by ghost 13
  • Easier extending/replacing of key algorithms

    Easier extending/replacing of key algorithms

    Changed some code to make jwk algorithm implementations easily extendable.

    If you want to replace a certain key implementation you only do jwk.ALGORITHMS.register_key("[algorithm name]", [key class]) and from that moment on the algorithm will use a different class to do everything.

    While doing it, made some stuff a bit more pythonic.

    opened by friedcell 13
  • crytography library

    crytography library

    I ended up here because of PyJWT but I also needed jwk stuff. I noticed PyJWT uses cryptography for some algorithm support. I guess Google App Engine requires PyCrypto as you mention but perhaps python-jose should also support cryptography. For example pycrypto hasn't had a commit in 2 years whereas cryptography repository is active.

    Just a thought! I might be interested in pitching in as well.

    opened by davemo88 13
  • Add message about lack of X.509 certificate support in documentation

    Add message about lack of X.509 certificate support in documentation

    I get this error when using algorithms='RS256' on google app engine.

    Full stack trace

    Traceback (most recent call last):
      File "/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/google/appengine/tools/devappserver2/python/request_handler.py", line 226, in handle_interactive_request
        exec(compiled_code, self._command_globals)
      File "<string>", line 12, in <module>
      File "lib/jose/jwt.py", line 121, in decode
        payload = jws.verify(token, key, algorithms, verify=verify_signature)
      File "lib/jose/jws.py", line 75, in verify
        _verify_signature(signing_input, header, signature, key, algorithms)
      File "lib/jose/jws.py", line 218, in _verify_signature
        key = jwk.construct(key, alg)
      File "lib/jose/jwk.py", line 65, in construct
        return RSAKey(key_data, algorithm)
      File "lib/jose/jwk.py", line 201, in __init__
        raise JWKError(e)
    JWKError: RSA key format is not supported
    
    docs 
    opened by anjorinjnr 13
  • pyjwt verifies token while python-jose fails

    pyjwt verifies token while python-jose fails

    This pyjwt example works;

    import jwt
    
    public_key = "-----BEGIN PUBLIC KEY-----\nMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAumZZl1U3GFFZyVTRmHLg\nb1II9+fOIqg9CT4gGDyfLglsPMBV3m6G88KhgiStpnY/nmR/yx0PewIBYPJNEC6x\nxdKxDbKkIA7oZz+P+I1qJwYQsyhIfmVd9IwGIebYu1ZNrlJmseu4axi+Q3NbjRs4\nsvXDt/WF4bkmGIvdlt35xta7+Dj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91Zc-L13ZNEpaxtNH95IKhn7XWD0vWvmnjYvHH4xe7iuOE-9zg9QTtb4tJvSdfkRYakfuJ-cqHaHOYFUu50n-rVs8H6Rr_fi_vohxC7ksdglhytg7K0COtvLSiJAFoZpuUW8QPF2lA"
    
    decoded_payload = jwt.decode(token, key=public_key, algorithms=['RS256'])
    

    While the same example with python-jose fails

    from jose import jwk
    from jose.utils import base64url_decode
    token = "eyJraWQiOiJ3bXF3Q2ttbVFubll1RXJEVGU2MDVOWUdMR0VTSW5iWUVmd3ZBeXJHc053PSIsImFsZyI6IlJTMjU2In0.eyJzdWIiOiJiMTMzZWQ0ZC02ZmUwLTQ0YjgtYjZiOS00YWY4NmJkMDYzMmQiLCJldmVudF9pZCI6IjcwNGEzODc3LTU0NGMtMTFlOC04YzRjLTZkNDNmZDlhNDg2YiIsInRva2VuX3VzZSI6ImFjY2VzcyIsInNjb3BlIjoiYXdzLmNvZ25pdG8uc2lnbmluLnVzZXIuYWRtaW4iLCJhdXRoX3RpbWUiOjE1MjU5NTQ3OTEsImlzcyI6Imh0dHBzOlwvXC9jb2duaXRvLWlkcC51cy1lYXN0LTEuYW1hem9uYXdzLmNvbVwvdXMtZWFzdC0xX21yazRSeWpZeiIsImV4cCI6MTUyNTk1ODM5MSwiaWF0IjoxNTI1OTU0NzkxLCJqdGkiOiJjN2EzZjE1MC1jM2I3LTQzOWQtOWRiNS1jNzMxNDgzNzc3MjIiLCJjbGllbnRfaWQiOiI2dXBlNm5kdW5ka3Y3ZjVpOWpsbzZhOHAydCIsInVzZXJuYW1lIjoiam9uYXRoYW5rb3NnZWkxMDAwQGdtYWlsLmNvbSJ9.extzT3KMtocdKmuNgpUpOAUe2WgOmEV2TbO4yWS8nnNzugIlYx93od38WKxLR66x1qTJVv-YQ-Yuk0pt2Nh-bWbYbOmYpURNBAVeFoLILxOMcGtboRI8ecBN57KZt6EQZl9_4gJmSqYDC3yXPBWyZ1MpDItaZCEbOEHIg8CEoCgTyeo5H_-AH7jBBSOLJF1rzdqntVkaVeCO91Zc-L13ZNEpaxtNH95IKhn7XWD0vWvmnjYvHH4xe7iuOE-9zg9QTtb4tJvSdfkRYakfuJ-cqHaHOYFUu50n-rVs8H6Rr_fi_vohxC7ksdglhytg7K0COtvLSiJAFoZpuUW8QPF2lA"
    rsa_key = {"alg":"RS256","e":"AQAB","kid":"wmqwCkmmQnnYuErDTe605NYGLGESInbYEfwvAyrGsNw=","kty":"RSA","n":"umZZl1U3GFFZyVTRmHLgb1II9-fOIqg9CT4gGDyfLglsPMBV3m6G88KhgiStpnY_nmR_yx0PewIBYPJNEC6xxdKxDbKkIA7oZz-P-I1qJwYQsyhIfmVd9IwGIebYu1ZNrlJmseu4axi-Q3NbjRs4svXDt_WF4bkmGIvdlt35xta7-Djo-WiGWfFZBaurnDZqtIZ4xl_CJW0rByX1hBHSUn_sS4JL8YUnPC8vLDUXlG5sLH_7BTI1VMtpWWqROnY9B_J8fR6oDdaSWP_BaYQQr8g6ye3a95zpaTweTNnom2VMgj9g23qPYrKD9zXL4oXTjjTb0MbUHRLP8FcYI7E5Sw","use":"sig"}
    key = jwk.construct(rsa_key)
    message, encoded_sig = token.rsplit('.', 1)
    decoded_sig = base64url_decode(encoded_sig.encode('utf-8'))
    key.verify(message, decoded_sig)
    

    That is key.verify returns False

    opened by jonathan-kosgei 11
  • Avoid loading python-ecdsa when using the cryptography backend

    Avoid loading python-ecdsa when using the cryptography backend

    In #117 dependency on ecdsa cryptography backend was removed, however it is still loaded even when not used. Since ecdsa has a load time performance penalty when gmpy2 is not installed, this can be a bit painful on embedded systems.

    We can avoid all this overhead and check to see if the key object hasattr to_pem instead since we only care of these if ecdsa has already been loaded by something else.

    opened by bdraco 10
  • Remove pycrypto/dome dependency on python-rsa

    Remove pycrypto/dome dependency on python-rsa

    This removes the cross-dependency of the pycrypto/dome backend on the python-rsa backend by moving ASN1 parsing to translate between PKCS1 and PKCS8 to a separate module that is now used by both pycrypto/dome and python-rsa backends.

    This makes pyasn1 a direct dependency of the pycrypto/dome backend (previously transient through python-rsa), but removes its dependency on python-rsa.

    CI also now tests the pycryto/dome backends after uninstalling python-rsa to make sure that this dependency is actually severed.

    opened by mattsb42-aws 10
  • Cannot run setup.py if setup.py is not in sys.path

    Cannot run setup.py if setup.py is not in sys.path

    setup.py can only currently be run if the jose can be imported. It is presumably assumed that the source root will be somewhere near the top of sys.path but this is not always the case.

    There are, therefore, two failure modes possible. If python-jose is not already installed, setup.py cannot be run at all. If python-jose is installed, then the version from the installed copy is used to generate the version for setup.py.

    Switching to using setup.cfg:

    [metadata]
    version = attr: jose.__version__
    

    allows setup.py to be run even if the source root is not on the path.

    bug help wanted 
    opened by mrginglymus 9
  • Import Mapping Error

    Import Mapping Error

    Hi. Please change 6-th line in jwt.py form from collections import Mapping to

    try:
        from collections.abc import Mapping
    except ImportError:
        from collections import Mapping
    

    And change 6-th line in jws.py from from collections import Mapping, Iterable to

    try:
        from collections.abc import Mapping, Iterable
    except ImportError:
        from collections import Mapping, Iterable
    
    opened by sazhyk 0
  • Add

    Add "algorithm mismatch" error to improve jws

    Upstream libraries that depend on jws.verify() break when the upstream keys contain a mixed set of algorithms. This is a nominal occurance for OIDC servers and should be properly handled.

    opened by tsweeney-dust 2
  • OpenSSL org published a critical vulnerability alert in OpenSSL 3.0 library (CVE-2022-3602)

    OpenSSL org published a critical vulnerability alert in OpenSSL 3.0 library (CVE-2022-3602)

    Hi i think this also effect you cause you are depende on Python Cryptography library cryptography = cryptography >=3.4.0 and it has this vulnerability (CVE-2022-3602) can you update to latest version

    opened by yaronbenezra 0
  • Feature request: Allow multiple audiences for JWT

    Feature request: Allow multiple audiences for JWT

    Hi,

    We'd like to accept multiple audiences, but jwt.decode() does not support an iterable. This is supported in PyJWT, and the _validate_aud() seems to already accept a list of audiences from the token.

    I'd happily submit a PR if accepted.

    opened by JonasKs 0
Releases(3.3.0)
Owner
Michael Davis
Michael Davis
Multi-user accounts for Django projects

django-organizations Summary Groups and multi-user account management Author Ben Lopatin (http://benlopatin.com) Status Separate individual user ident

Ben Lopatin 1.1k Jan 02, 2023
Authware API wrapper for Python 3.5+

AuthwarePy Asynchronous wrapper for Authware in Python 3.5+ View our documentation 📲 Installation Run this to install the library via pip: pip instal

Authware 3 Feb 09, 2022
Graphical Password Authentication System.

Graphical Password Authentication System. This is used to increase the protection/security of a website. Our system is divided into further 4 layers of protection. Each layer is totally different and

Hassan Shahzad 12 Dec 16, 2022
A host-guest based app in which host can CREATE the room. and guest can join room with room code and vote for song to skip. User is authenticated using Spotify API

A host-guest based app in which host can CREATE the room. and guest can join room with room code and vote for song to skip. User is authenticated using Spotify API

Aman Raj 5 May 10, 2022
Python One-Time Password Library

PyOTP - The Python One-Time Password Library PyOTP is a Python library for generating and verifying one-time passwords. It can be used to implement tw

PyAuth 2.2k Dec 26, 2022
Alisue 299 Dec 06, 2022
A simple Boilerplate to Setup Authentication using Django-allauth 🚀

A simple Boilerplate to Setup Authentication using Django-allauth, with a custom template for login and registration using django-crispy-forms.

Yasser Tahiri 13 May 13, 2022
Library - Recent and favorite documents

Thingy Thingy is used to quickly access recent and favorite documents. It's an XApp so it can work in any distribution and many desktop environments (

Linux Mint 23 Sep 11, 2022
A wagtail plugin to replace the login by an OAuth2.0 Authorization Server

Wagtail OAuth2.0 Login Plugin to replace Wagtail default login by an OAuth2.0 Authorization Server. What is wagtail-oauth2 OAuth2.0 is an authorizatio

Gandi 7 Oct 07, 2022
AddressBookApp - Address Book App in Django

AddressBookApp Application Name Address Book App in Django, 2022 Technologies La

Joshua K 1 Aug 18, 2022
Foundation Auth Proxy is an abstraction on Foundations' authentication layer and is used to authenticate requests to Atlas's REST API.

foundations-auth-proxy Setup By default the server runs on http://0.0.0.0:5558. This can be changed via the arguments. Arguments: '-H' or '--host': ho

Dessa - Open Source 2 Jul 03, 2020
Automatizando a criação de DAGs usando Jinja e YAML

Automatizando a criação de DAGs no Airflow usando Jinja e YAML Arquitetura do Repo: Pastas por contexto de negócio (ex: Marketing, Analytics, HR, etc)

Arthur Henrique Dell' Antonia 5 Oct 19, 2021
:couple: Multi-user accounts for Django projects

django-organizations Summary Groups and multi-user account management Author Ben Lopatin (http://benlopatin.com) Status Separate individual user ident

Ben Lopatin 1.1k Jan 09, 2023
This Python based program checks your CC Stripe Auth 1$ Based Checker

CC-Checker This Python based program checks your CC Stripe Auth 1$ Based Checker About Author Coded by xBlackx Reach Me On Telegram @xBlackx_Coder jOI

xBlackxCoder 11 Nov 20, 2022
Awesome Django authorization, without the database

rules rules is a tiny but powerful app providing object-level permissions to Django, without requiring a database. At its core, it is a generic framew

1.6k Dec 30, 2022
Simple Login - Login Extension for Flask - maintainer @cuducos

Login Extension for Flask The simplest way to add login to flask! How it works First, install it from PyPI: $ pip install flask_simplelogin Then, use

Flask Extensions 181 Jan 01, 2023
Social auth made simple

Python Social Auth Python Social Auth is an easy-to-setup social authentication/registration mechanism with support for several frameworks and auth pr

Matías Aguirre 2.8k Dec 24, 2022
Authentication, JWT, and permission scoping for Sanic

Sanic JWT Sanic JWT adds authentication protection and endpoints to Sanic. It is both easy to get up and running, and extensible for the developer. It

Adam Hopkins 229 Jan 05, 2023
This script helps you log in to your LMS account and enter the currently running session

This script helps you log in to your LMS account and enter the currently running session, all in a second

Ali Ebrahimi 5 Sep 01, 2022
An introduction of Markov decision process (MDP) and two algorithms that solve MDPs (value iteration, policy iteration) along with their Python implementations.

Markov Decision Process A Markov decision process (MDP), by definition, is a sequential decision problem for a fully observable, stochastic environmen

Yu Shen 31 Dec 30, 2022