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/WF4bkmGIvdlt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VkaVeCO91Zc-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
A generic, spec-compliant, thorough implementation of the OAuth request-signing logic

OAuthLib - Python Framework for OAuth1 & OAuth2 *A generic, spec-compliant, thorough implementation of the OAuth request-signing logic for Python 3.5+

OAuthlib 2.5k Jan 2, 2023
Implementation of Supervised Contrastive Learning with AMP, EMA, SWA, and many other tricks

SupCon-Framework The repo is an implementation of Supervised Contrastive Learning. It's based on another implementation, but with several differencies

Ivan Panshin 132 Dec 14, 2022
A generic, spec-compliant, thorough implementation of the OAuth request-signing logic

OAuthLib - Python Framework for OAuth1 & OAuth2 *A generic, spec-compliant, thorough implementation of the OAuth request-signing logic for Python 3.5+

OAuthlib 2.5k Jan 1, 2023
REST implementation of Django authentication system.

djoser REST implementation of Django authentication system. djoser library provides a set of Django Rest Framework views to handle basic actions such

Sunscrapers 2.2k Jan 1, 2023
Flask Implementation of a login page and some basic functionality.

login_page Flask Implementation of a login page and some basic functionality. How to Run $ chmod +x run.sh setup.sh $ # run setup.sh only if the datab

null 3 Jun 3, 2021
Easy and secure implementation of Azure AD for your FastAPI APIs šŸ”’ Single- and multi-tenant support.

Easy and secure implementation of Azure AD for your FastAPI APIs ?? Single- and multi-tenant support.

Intility 220 Jan 5, 2023
Simple implementation of authentication in projects using FastAPI

Fast Auth Facilita implementaĆ§Ć£o de um sistema de autenticaĆ§Ć£o bĆ”sico e uso de uma sessĆ£o de banco de dados em projetos com tFastAPi. InstalaĆ§Ć£o e con

null 3 Jan 8, 2022
Official implementation of the AAAI 2022 paper "Learning Token-based Representation for Image Retrieval"

Token: Token-based Representation for Image Retrieval PyTorch training code for Token-based Representation for Image Retrieval. We propose a joint loc

Hui Wu 42 Dec 6, 2022
Login-python - Login system made in Python, using native libraries

login-python Sistema de login feito 100% em Python, utilizando bibliotecas nativ

Nicholas Gabriel De Matos Leal 2 Jan 28, 2022
The ultimate Python library in building OAuth, OpenID Connect clients and servers. JWS,JWE,JWK,JWA,JWT included.

Authlib The ultimate Python library in building OAuth and OpenID Connect servers. JWS, JWK, JWA, JWT are included. Authlib is compatible with Python2.

Hsiaoming Yang 3.4k Jan 4, 2023
Python module for generating and verifying JSON Web Tokens

python-jwt 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

David Halls 210 Dec 24, 2022
OAuthlib support for Python-Requests!

Requests-OAuthlib This project provides first-class OAuth library support for Requests. The OAuth 1 workflow OAuth 1 can seem overly complicated and i

null 1.6k Dec 28, 2022
Google Auth Python Library

Google Auth Python Library This library simplifies using Google's various server-to-server authentication mechanisms to access Google APIs. Installing

Google APIs 598 Jan 7, 2023
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
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
Django CAS 1.0/2.0/3.0 client authentication library, support Django 2.0, 2.1, 2.2, 3.0 and Python 3.5+

django-cas-ng django-cas-ng is Django CAS (Central Authentication Service) 1.0/2.0/3.0 client library to support SSO (Single Sign On) and Single Logou

django-cas-ng 347 Dec 18, 2022
This is a Python library for accessing resources protected by OAuth 2.0.

This is a client library for accessing resources protected by OAuth 2.0. Note: oauth2client is now deprecated. No more features will be added to the l

Google APIs 787 Dec 13, 2022
A Python library for OAuth 1.0/a, 2.0, and Ofly.

Rauth A simple Python OAuth 1.0/a, OAuth 2.0, and Ofly consumer library built on top of Requests. Features Supports OAuth 1.0/a, 2.0 and Ofly Service

litl 1.6k Dec 8, 2022
The ultimate Python library in building OAuth, OpenID Connect clients and servers. JWS,JWE,JWK,JWA,JWT included.

Authlib The ultimate Python library in building OAuth and OpenID Connect servers. JWS, JWK, JWA, JWT are included. Authlib is compatible with Python2.

Hsiaoming Yang 2.3k Feb 17, 2021