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
An open source Flask extension that provides JWT support (with batteries included)!

Flask-JWT-Extended Features Flask-JWT-Extended not only adds support for using JSON Web Tokens (JWT) to Flask for protecting views, but also many help

Landon Gilbert-Bland 1.4k Jan 04, 2023
FastAPI-Login tries to provide similar functionality as Flask-Login does.

FastAPI-Login FastAPI-Login tries to provide similar functionality as Flask-Login does. Installation $ pip install fastapi-login Usage To begin we hav

417 Jan 07, 2023
Toolkit for Pyramid, a Pylons Project, to add Authentication and Authorization using Velruse (OAuth) and/or a local database, CSRF, ReCaptcha, Sessions, Flash messages and I18N

Apex Authentication, Form Library, I18N/L10N, Flash Message Template (not associated with Pyramid, a Pylons project) Uses alchemy Authentication Authe

95 Nov 28, 2022
Login System Using Django

Login System Django

Nandini Chhajed 6 Dec 12, 2021
Django Auth Protection This package logout users from the system by changing the password in Simple JWT REST API.

Django Auth Protection Django Auth Protection This package logout users from the system by changing the password in REST API. Why Django Auth Protecti

Iman Karimi 5 Oct 26, 2022
Python's simple login system concept - Advanced level

Simple login system with Python - For beginners Creating a simple login system using python for beginners this repository aims to provide a simple ove

Low_Scarlet 1 Dec 13, 2021
PetitPotam - Coerce NTLM authentication from Windows hosts

Python implementation for PetitPotam

ollypwn 137 Dec 28, 2022
Pingo provides a uniform API to program devices like the Raspberry Pi, BeagleBone Black, pcDuino etc.

Pingo provides a uniform API to program devices like the Raspberry Pi, BeagleBone Black, pcDuino etc. just like the Python DBAPI provides an uniform API for database programming in Python.

Garoa Hacker Clube 12 May 22, 2022
A simple model based API maker written in Python and based on Django and Django REST Framework

Fast DRF Fast DRF is a small library for making API faster with Django and Django REST Framework. It's easy and configurable. Full Documentation here

Mohammad Ashraful Islam 18 Oct 05, 2022
Complete Two-Factor Authentication for Django providing the easiest integration into most Django projects.

Django Two-Factor Authentication Complete Two-Factor Authentication for Django. Built on top of the one-time password framework django-otp and Django'

Bouke Haarsma 1.3k Jan 04, 2023
Automatic login utility of free Wi-Fi captive portals

wicafe Automatic login utility of free Wi-Fi captive portals Disclaimer: read and grant the Terms of Service of Wi-Fi services before using it! This u

Takumi Sueda 8 May 31, 2022
A flask extension for managing permissions and scopes

Flask-Pundit A simple flask extension to organize resource authorization and scoping. This extension is heavily inspired by the ruby Pundit library. I

Anurag Chaudhury 49 Dec 23, 2022
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
JWT authentication for Pyramid

JWT authentication for Pyramid This package implements an authentication policy for Pyramid that using JSON Web Tokens. This standard (RFC 7519) is of

Wichert Akkerman 73 Dec 03, 2021
Basic auth for Django.

Basic auth for Django.

bichanna 2 Mar 25, 2022
Simplifying third-party authentication for web applications.

Velruse is a set of authentication routines that provide a unified way to have a website user authenticate to a variety of different identity provider

Ben Bangert 253 Nov 14, 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
Object Moderation Layer

django-oml Welcome to the documentation for django-oml! OML means Object Moderation Layer, the idea is to have a mixin model that allows you to modera

Angel VelƔsquez 12 Aug 22, 2019
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
Kube OpenID Connect is an application that can be used to easily enable authentication flows via OIDC for a kubernetes cluster

Kube OpenID Connect is an application that can be used to easily enable authentication flows via OIDC for a kubernetes cluster. Kubernetes supports OpenID Connect Tokens as a way to identify users wh

7 Nov 20, 2022