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
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
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 09, 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
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
Corsair_scan is a security tool to test Cross-Origin Resource Sharing (CORS).

Welcome to Corsair_scan Corsair_scan is a security tool to test Cross-Origin Resource Sharing (CORS) misconfigurations. CORS is a mechanism that allow

Santander Security Research 116 Nov 09, 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
Basic auth for Django.

Basic auth for Django.

bichanna 2 Mar 25, 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 29, 2022
蓝鲸用户管理是蓝鲸智云提供的企业组织架构和用户管理解决方案,为企业统一登录提供认证源服务。

蓝鲸用户管理 简体中文 | English 蓝鲸用户管理是蓝鲸智云提供的企业组织架构和用户管理解决方案,为企业统一登录提供认证源服务。 总览 架构设计 代码目录 功能 支持多层级的组织架构管理 支持通过多种方式同步数据:OpenLDAP、Microsoft Active Directory(MAD)

腾讯蓝鲸 35 Dec 14, 2022
MikroTik Authentication POCs

Proofs of concept which successfully authenticate with MikroTik Winbox and MAC Telnet servers running on RouterOS version 6.45.1+

Margin Research 56 Dec 08, 2022
Django x Elasticsearch Templates

Django x Elasticsearch Requirements Python 3.7 Django = 3 Elasticsearch 7.15 Setup Elasticsearch Install via brew Install brew tap elastic/tap brew

Aji Pratama 0 May 22, 2022
Authentication with fastapi and jwt cd realistic

Authentication with fastapi and jwt cd realistic Dependencies bcrypt==3.1.7 data

Fredh Macau 1 Jan 04, 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 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
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 05, 2023
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 02, 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
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
An extension of django rest framework, providing a configurable password reset strategy

Django Rest Password Reset This python package provides a simple password reset strategy for django rest framework, where users can request password r

Anexia 363 Dec 24, 2022
Strong, Simple, and Precise security for Flask APIs (using jwt)

flask-praetorian Strong, Simple, and Precise security for Flask APIs API security should be strong, simple, and precise like a Roman Legionary. This p

Tucker Beck 321 Dec 18, 2022