Giter Club home page Giter Club logo

python-jwt's Introduction

image

image

image

python-jwt

python-jwt is a JSON Web Token (JWT) implementation in Python developed by Gehirn Inc.

Examples

import json
from datetime import datetime, timedelta, timezone

from jwt import (
    JWT,
    jwk_from_dict,
    jwk_from_pem,
)
from jwt.utils import get_int_from_datetime


instance = JWT()

message = {
    'iss': 'https://example.com/',
    'sub': 'yosida95',
    'iat': get_int_from_datetime(datetime.now(timezone.utc)),
    'exp': get_int_from_datetime(
        datetime.now(timezone.utc) + timedelta(hours=1)),
}

"""
Encode the message to JWT(JWS).
"""

# Load a RSA key from a JWK dict.
signing_key = jwk_from_dict({
    'kty': 'RSA',
    'e': 'AQAB',
    'n': '...',
    'd': '...'})
# Or load a RSA key from a PEM file.
with open('rsa_private_key.pem', 'rb') as fh:
    signing_key = jwk_from_pem(fh.read())
# You can also load an octet key in the same manner as the RSA.
# signing_key = jwk_from_dict({'kty': 'oct', 'k': '...'})

compact_jws = instance.encode(message, signing_key, alg='RS256')

"""
Decode the JWT with verifying the signature.
"""

# Load a public key from PEM file corresponding to the signing private key.
with open('rsa_public_key.json', 'r') as fh:
    verifying_key = jwk_from_dict(json.load(fh))

message_received = instance.decode(
    compact_jws, verifying_key, do_time_check=True)

"""
Successfuly retrieved the `message` from the `compact_jws`
"""
assert message == message_received

Installation

You can install python-jwt with pip.

$ pip install jwt

Implementation Details

Supported Algorithms

  • Unsecured
    • none (disabled by default for security)
  • Symmetric
    • HS256
    • HS384
    • HS512
  • Asymmetric
    • PS256
    • PS384
    • PS512
    • RS256
    • RS384
    • RS512

Supported Python Versions

  • Python 3.6+

License

python-jwt is licensed under the Apache License version 2. See ./LICENSE.rst.

python-jwt's People

Contributors

castixgithub avatar dependabot[bot] avatar dreamsorcerer avatar egon0 avatar ehooo avatar fatlotus avatar gothackovo avatar hairychris avatar jcollado avatar sjortiz avatar teeberg avatar yosida95 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

python-jwt's Issues

Simple way to enable none algorithm for unit testing

I'd like to temporarily enable the none algorithm to create unsigned JWTs as part of my unit tests. I didn't manage to do this, can you please add an info (or a function) to do this? Or add a dedicate encodeUnsignedJWT function?

Relax or remove upper bound for cryptography

PR #45 changed version range of cryptography to cryptography >= 3.1, < 36.0. The new range is still problematic. Cryptography has adopted a new version scheme. New major version will be released more often. I expect release 36.0.0 in a couple of days. You can find more details in pyca/cryptography#6345 .

Could you please relax or remove the upper bound?

name clash

Thanks to this bug in pip, installing pyjwt and jwt at the same time causes a whole lot of issues with no warning whatsoever to the poor user. Please see pypa/pip#4625 and jpadilla/pyjwt#282 for details.

And pretty please consider talk with the author of the other package and agree on a unique namespace.

How to generate rsa_public_key.json?

In your example code you load a public key from rsa_public_key.json. How is this JSON file generated?

I have no problems generating a PEM from the private key for signing. But how to generte the input for verifying?

python-jwt will install in python 2 under Mac OS

On Mac OS 10.13.5, python-jwt will install via pip to a python2 installation, seemingly successfully (see below). Installing to a python3 installation using pip3 works as expected. Installing to python2 under Ubuntu 16.04 fails at building wheel for cryptography step. Seems like a more robust version check is needed.

(test-venv) username@hostname:~/test-venv$ python --version
Python 2.7.10
(test-venv) username@hostname:~/test-venv$ pip install jwt
Collecting jwt
Collecting cryptography==1.7.2 (from jwt)
  Using cached https://files.pythonhosted.org/packages/51/d9/91266ca5bc54de4882d8a2e836a3038e4cb9a1cc189a9c745516dc685ea1/cryptography-1.7.2-cp27-cp27m-macosx_10_6_intel.whl
Collecting typing==3.5.3.0 (from jwt)
Collecting six>=1.4.1 (from cryptography==1.7.2->jwt)
  Using cached https://files.pythonhosted.org/packages/67/4b/141a581104b1f6397bfa78ac9d43d8ad29a7ca43ea90a2d863fe3056e86a/six-1.11.0-py2.py3-none-any.whl
Requirement already satisfied: setuptools>=11.3 in ./lib/python2.7/site-packages (from cryptography==1.7.2->jwt) (40.0.0)
Collecting pyasn1>=0.1.8 (from cryptography==1.7.2->jwt)
  Using cached https://files.pythonhosted.org/packages/a0/70/2c27740f08e477499ce19eefe05dbcae6f19fdc49e9e82ce4768be0643b9/pyasn1-0.4.3-py2.py3-none-any.whl
Collecting cffi>=1.4.1 (from cryptography==1.7.2->jwt)
  Using cached https://files.pythonhosted.org/packages/7e/4a/b647e46faaa2dcfb16069b6aad2d8509982fd63710a325b8ad7db80f18be/cffi-1.11.5-cp27-cp27m-macosx_10_6_intel.whl
Collecting enum34 (from cryptography==1.7.2->jwt)
  Using cached https://files.pythonhosted.org/packages/c5/db/e56e6b4bbac7c4a06de1c50de6fe1ef3810018ae11732a50f15f62c7d050/enum34-1.1.6-py2-none-any.whl
Collecting ipaddress (from cryptography==1.7.2->jwt)
  Using cached https://files.pythonhosted.org/packages/fc/d0/7fc3a811e011d4b388be48a0e381db8d990042df54aa4ef4599a31d39853/ipaddress-1.0.22-py2.py3-none-any.whl
Collecting idna>=2.0 (from cryptography==1.7.2->jwt)
  Using cached https://files.pythonhosted.org/packages/4b/2a/0276479a4b3caeb8a8c1af2f8e4355746a97fab05a372e4a2c6a6b876165/idna-2.7-py2.py3-none-any.whl
Collecting pycparser (from cffi>=1.4.1->cryptography==1.7.2->jwt)
Installing collected packages: six, pyasn1, pycparser, cffi, enum34, ipaddress, idna, cryptography, typing, jwt
Successfully installed cffi-1.11.5 cryptography-1.7.2 enum34-1.1.6 idna-2.7 ipaddress-1.0.22 jwt-0.5.2 pyasn1-0.4.3 pycparser-2.18 six-1.11.0 typing-3.5.3.0
(test-venv) username@hostname:~/test-venv$ python
Python 2.7.10 (default, Oct  6 2017, 22:29:07) 
[GCC 4.2.1 Compatible Apple LLVM 9.0.0 (clang-900.0.31)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import jwt
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/Users/username/test-venv/lib/python2.7/site-packages/jwt/__init__.py", line 17, in <module>
    from .jwk import (
  File "/Users/username/test-venv/lib/python2.7/site-packages/jwt/jwk.py", line 60
    def is_sign_key(self) -> bool:
                          ^
SyntaxError: invalid syntax

assert isinstance(..., str) differs in Python 2.x and Python 3.x

The various assertions in the codebase that assert isinstance(..., str) will behave differently in Python 2.x and Python 3.x. The assertions may work now on tested examples but their behaviour is different. In Python 2.x it'll assert that a sequence of bytes is passed in wheres in Python 3.x it'll assert a Unicode string is passed in. So these assertions should be adapted to use basestring instead.

AttributeError: 'dict' object has no attribute '_jws'

AttributeError: 'dict' object has no attribute '_jws'

got this error :

File "E:\github\MyGits\TDA\rest_server_sql.py", line 113, in login
token = jwt.JWT.encode({'public_id' : user.public_id, 'exp' : datetime.datetime.utcnow() + datetime.timedelta(minutes=30)}, app.config['SECRET_KEY'])
File "E:\github\MyGits\TDA\venv_tda\lib\site-packages\jwt\jwt.py", line 44, in encode
return self._jws.encode(message, key, alg, optional_headers)
AttributeError: 'dict' object has no attribute '_jws'

while generating token:
token = jwt.JWT.encode({'public_id' : user.public_id, 'exp' : datetime.datetime.utcnow() + datetime.timedelta(minutes=30)}, app.config['SECRET_KEY'])

support for cryptography 2

Please provide a support for cryptography package in newest version (2.*).

Requirement cryptography<2.* causes dependency clash in our project.

Can't perform makemigrations Jango when using JWT

Hi everyone, i faced with problem, which can't let me perform makemigrations when i'm using JWT.

The error is:
from jwt import JWT, jwk_from_pem ImportError: cannot import name JWT

In the file i just import JWT & jwk_from_pem
from jwt import JWT, jwk_from_pem
then using jwt = JWT()

In the settings.py
INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ..., 'rest_framework', 'jwt', ..., ]

What the cause of the error above?

TypeError: _EllipticCurvePublicKey.verify() takes 4 positional arguments but 5 were given

Trying to decode a jwt token which was encrypted with RS256

res = jwt.decode(
    jwt=token,
    key=SECRET,
    algorithms=["ES256","RS256",],
    options={
        "verify_signature": True,
        "require": get_required_fields(),
    }
)

getting this error:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/opt/venv/lib/python3.10/site-packages/jwt/api_jwt.py", line 168, in decode
    decoded = self.decode_complete(
  File "/opt/venv/lib/python3.10/site-packages/jwt/api_jwt.py", line 120, in decode_complete
    decoded = api_jws.decode_complete(
  File "/opt/venv/lib/python3.10/site-packages/jwt/api_jws.py", line 202, in decode_complete
    self._verify_signature(signing_input, header, signature, key, algorithms)
  File "/opt/venv/lib/python3.10/site-packages/jwt/api_jws.py", line 300, in _verify_signature
    if not alg_obj.verify(signing_input, key, signature):
  File "/opt/venv/lib/python3.10/site-packages/jwt/algorithms.py", line 377, in verify
    key.verify(sig, msg, padding.PKCS1v15(), self.hash_alg())
TypeError: _EllipticCurvePublicKey.verify() takes 4 positional arguments but 5 were given

versions:

# pip freeze | grep JWT
PyJWT==2.6.0
# pip freeze | grep cryptography
cryptography==38.0.3

Conflict with PyJWT

Hello,

There is a conflict between this package and the PyJWT (https://github.com/jpadilla/pyjwt), both packages are installed in the /dist-packages/jwt.

It could be good if the two teams could come up with some solution? Or can this package installed in a different way?

Kind regards
Attila

Import error in algorithms.py with 3.6.1

I have python 3.6.1. and jwt 0.5.1
I'm getting an import error. I don't know why.

File "/usr/local/lib/python3.6/dist-packages/requests/api.py", line 72, in get
   return request('get', url, params=params, **kwargs)
 File "/usr/local/lib/python3.6/dist-packages/requests/api.py", line 58, in request
   return session.request(method=method, url=url, **kwargs)
 File "/usr/local/lib/python3.6/dist-packages/requests/sessions.py", line 504, in request
   prep = self.prepare_request(req)
 File "/usr/local/lib/python3.6/dist-packages/requests/sessions.py", line 436, in prepare_request
   hooks=merge_hooks(request.hooks, self.hooks),
 File "/usr/local/lib/python3.6/dist-packages/requests/models.py", line 306, in prepare
   self.prepare_auth(auth, url)
 File "/usr/local/lib/python3.6/dist-packages/requests/models.py", line 543, in prepare_auth
   r = auth(self)
 File "/usr/local/lib/python3.6/dist-packages/requests_oauthlib/oauth1_auth.py", line 88, in __call__
   unicode(r.url), unicode(r.method), None, r.headers)
 File "/usr/local/lib/python3.6/dist-packages/oauthlib/oauth1/rfc5849/__init__.py", line 314, in sign
   ('oauth_signature', self.get_oauth_signature(request)))
 File "/usr/local/lib/python3.6/dist-packages/oauthlib/oauth1/rfc5849/__init__.py", line 151, in get_oauth_signature
   sig = self.SIGNATURE_METHODS[self.signature_method](base_string, self)
 File "/usr/local/lib/python3.6/dist-packages/oauthlib/oauth1/rfc5849/signature.py", line 505, in sign_rsa_sha1_with_client
   return sign_rsa_sha1(base_string, client.rsa_key)
 File "/usr/local/lib/python3.6/dist-packages/oauthlib/oauth1/rfc5849/signature.py", line 496, in sign_rsa_sha1
   alg = _jwt_rs1_signing_algorithm()
 File "/usr/local/lib/python3.6/dist-packages/oauthlib/oauth1/rfc5849/signature.py", line 473, in _jwt_rs1_signing_algorithm
   import jwt.algorithms as jwtalgo
 File "/usr/local/lib/python3.6/dist-packages/jwt/algorithms.py", line 5, in <module>
   from .exceptions import InvalidKeyError
ImportError: cannot import name 'InvalidKeyError'

Invalid Syntax: alg:str

Trying to import jwt==0.5.4 in Py2.7:

Python 2.7.12 (default, Nov 12 2018, 14:36:49) 
[GCC 5.4.0 20160609] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import jwt
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/home/johnli/.local/lib/python2.7/site-packages/jwt/__init__.py", line 17, in <module>
    from .jwa import std_hash_by_alg
  File "/home/johnli/.local/lib/python2.7/site-packages/jwt/jwa.py", line 31
    def std_hash_by_alg(alg: str) -> Callable[[bytes], object]:
                           ^
SyntaxError: invalid syntax

Unable to import under Python 3.8

(venv) wlad@hypervubu:~/projects/ehrbase/tests$ python
Python 3.8.2 (default, Apr 16 2020, 20:42:22) 
[GCC 9.2.1 20191008] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import json
>>> from datetime import datetime, timedelta, timezone
>>> from jwt import JWT
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ImportError: cannot import name 'JWT' from 'jwt' (unknown location)
>>> from jwt import jwt
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/home/wlad/.local/lib/python3.8/site-packages/jwt/jwt.py", line 22, in <module>
    from jwt.utils import (
ModuleNotFoundError: No module named 'jwt.utils

install_requires should fix dependencies to specific versions

The install_requires value in setup.py does not specify the exact versions (dependency==0.1.0) and / or version bounds (dependency<=0.2). This means that someone could install this project a year from now and it may not work because a dependency could have introduced a backwards incompatible change. It's therefore better to specify the versions and upgrade them yourself when you've verified that a newer version of a dependency works fine with this project.

how to use jwks?

I'm upgrading an out-of-date application from 0.3.x to 1.0, and I don't understand how to use JWKS now? Previously you could supply a JWKSet object to JWT and it would automatically fetch the correct key based on the keyid, but I don't see any methods in this codebase any more that call the JWKSet's filter_keys method. Am I missing something?

Fix for python 3.10 (collections interface)

Change required due to the collections interface starting with Python 3.10.

suggested patch - change this

from collections import Mapping

to this

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

cryptography <= 2.9.2 CVE

The cryptography package has a CVE assigned to it for versions <= 2.9.2. Whilst jwt may not be directly affected, other packages that import cryptography may be.
Would it be possible to upgrade to 3.x?

cryptography install fails

Please update cryptography dependency, because when building cryptography==1.7.2, the package fails (recent versions of openssl - 1.1.0g). I saw that in newer versions of cryptography the problem does not occur.

Improve documentation for symmetric keys

The README states that symmetric algorithms are supported but I haven't been able to figure out how to decode them with this library. Either I'm missing something or this hasn't been implemented yet.

Either way, appreciate any help on this.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.