Safely pass trusted data to untrusted environments and back.

Overview

ItsDangerous

... so better sign this

Various helpers to pass data to untrusted environments and to get it back safe and sound. Data is cryptographically signed to ensure that a token has not been tampered with.

It's possible to customize how data is serialized. Data is compressed as needed. A timestamp can be added and verified automatically while loading a token.

Installing

Install and update using pip:

pip install -U itsdangerous

A Simple Example

Here's how you could generate a token for transmitting a user's id and name between web requests.

from itsdangerous import URLSafeSerializer
auth_s = URLSafeSerializer("secret key", "auth")
token = auth_s.dumps({"id": 5, "name": "itsdangerous"})

print(token)
# eyJpZCI6NSwibmFtZSI6Iml0c2Rhbmdlcm91cyJ9.6YP6T0BaO67XP--9UzTrmurXSmg

data = auth_s.loads(token)
print(data["name"])
# itsdangerous

Donate

The Pallets organization develops and supports ItsDangerous and other popular packages. In order to grow the community of contributors and users, and allow the maintainers to devote more time to the projects, please donate today.

Links

Comments
  • why the exp and iat put in the header section of the jwt?

    why the exp and iat put in the header section of the jwt?

    I read the latest offical doc and font that exp and iat is usually put in the payload part instead of header section. should I use this or remove it and pyjwt instead??

    opened by ghost 17
  • Change of default algorithm may cause problems

    Change of default algorithm may cause problems

    I just wanted to share with you my experience that the change in the default signing algorithm from HS256 to HS512 can break things in case of JSONWebSignatureSerializer that need to be persistent (e.g. stored in a db).

    On our server, previously generated JWTs started causing BadSignature exceptions, resulting in authentication failure.

    opened by desmoteo 16
  • add typing with mypy

    add typing with mypy

    Implementation notes:

    • Didn't import types individually, used import typing as _t to shorten things.
    • Common types are aliased in a if TYPE_CHECKING: block and referenced as string names.
    • Only a few types (really just str_bytes) were common between modules, didn't bother with a common _typing module.
    • All generics that aren't in the common block are strings to avoid runtime cost. This won't be necessary once we drop 3.6.
    • The return_timestamp parameter of TimestampSigner.unsign changes the return type. To distinguish these, @overload is used, but because the method takes some other optional parameters, many overloads are needed to cover every combination. I added the overloads that matter, as mypy does use that to figure out a type elsewhere, but ignored the finding about incompatible overlap.
    • Flake8 has a special case so @typing.overload doesn't trigger a redefinition error, but it has to be literally typing.overload, _t.overload isn't recognized. So had to ignore that Flake8 finding.
    • Mypy doesn't allow assignment of modules or classes for Protocol, so Serializer.serializer has the Any type for now. See https://github.com/python/mypy/issues/5018.

    Findings and future work:

    • TimedSerializer.loads and loads_unsafe have incompatible signatures with Serializer.loads because extra parameters were added before the salt parameter. This violates the Liskov substitution principle, and should probably be migrated with *args and a deprecation warning at some point. I added a TODO in the code.

    • Between removing Python 2 compat helpers and adding typing, I'm more convinced that accepting bytes and str interchangeably everywhere is not good. Python 3 emphasizes understanding the boundary between the two.

      Because pretty much every single point in the ItsDangerous API accepts either, want_bytes is called over and over again, even where it's redundant because an earlier function already called it. I already moved wants_bytes around to get a few spots that were missed. This isn't a huge deal in ItsDangerous, but it's probably hurting performance in Werkzeug where it happens much more often.

      It's still probably useful to accept both as the data passed to Serializer.loads, Signer.sign, and Singer.unsign, since you might be signing either bytes or text, and received data to be loaded might be bytes or text (ASGI vs WSGI, for example). Everything else should probably be bytes only since that's how they're used.

    cc @pgjones

    opened by davidism 14
  • Timestamp signatures from 0.x incompatible with 1.1

    Timestamp signatures from 0.x incompatible with 1.1

    Perhaps related to #115, we find that signatures produced on itsdangerous 0.24 are incompatible with 1.1. For example:

    $ pip-run -q itsdangerous==0.24 -- -c "import itsdangerous; print(itsdangerous.Signer(b'secret-key').sign(b'my string').decode('ascii'))"
    my string.wh6tMHxLgJqB6oY1uT73iMlyrOA
    $ echo 'my string.wh6tMHxLgJqB6oY1uT73iMlyrOA' | pip-run -q itsdangerous==1.1 -- -c "import itsdangerous, sys; print(itsdangerous.Signer('secret-key').unsign(sys.stdin.read()))"
    Traceback (most recent call last):
      File "<string>", line 1, in <module>
      File "/var/folders/c6/v7hnmq453xb6p2dbz1gqc6rr0000gn/T/pip-run-0f22xq6u/itsdangerous/signer.py", line 169, in unsign
        raise BadSignature("Signature %r does not match" % sig, payload=value)
    itsdangerous.exc.BadSignature: Signature b'wh6tMHxLgJqB6oY1uT73iMlyrOA\n' does not match
    

    Additionally, the engineer reports that

    the expiration time is encoded and decoded differently [between versions]

    This incompatibility has led our engineers to believe that it's necessary to upgrade all clients and producers simultaneously.

    Is this incompatibility by design? Is there an approach that would allow the various signers/verifiers to use different versions of itsdangerous?

    opened by jaraco 11
  • When used in a Django environment, automatically use settings.SECRET_KEY

    When used in a Django environment, automatically use settings.SECRET_KEY

    Especially since this is based on Django's signing module.

    Alternatively, you could let us set a default secret key to use, which would be the more generally useful implementation.

    It's just not very DRY to pass this information in everywhere that you use a signer in your code.

    opened by fletom 11
  • 1.0.0 Removed

    1.0.0 Removed

    I’m sorry for the inconvenience caused but I missed that there was a signature change that made it into 1.0. I yanked the release now because this change had some cery bad consequences and yanking the release is less risky in comparison.

    If someone already uses 1.0 roll back to 0.24 and set the hash algoritm to sha 512 if needed. Note though that it will be unlikely we switch to that algorithm going forward.

    I will figure out a way forward over the weekend.

    For more information see #111

    opened by mitsuhiko 10
  • Change the default from SHA1

    Change the default from SHA1

    SHA1 has been demonstrated to have collisions in the wild (https://security.googleblog.com/2017/02/announcing-first-sha1-collision.html), the default should be changed to e.g. SHA256

    opened by devnul3 10
  • TimestampSigner writes local-time timestamps and reads them as UTC

    TimestampSigner writes local-time timestamps and reads them as UTC

    TimestampSigner uses int(time.time()) to create timestamps, which will use the local timezone. However, it uses datetime.utcfromtimestamp to convert them into datetime objects, which will create naive datetime objects by interpreting the timestamp in the UTC timezone.

    The fix should be to always write UTC timestamps. See this StackOverflow question for examples how to do this properly.

    To be clear, this is in reference to this current code:

        def get_timestamp(self):
            """Returns the current timestamp. The function must return an
            integer.
            """
            return int(time.time())
    
        def timestamp_to_datetime(self, ts):
            """Used to convert the timestamp from :meth:`get_timestamp` into
            a datetime object.
            """
            return datetime.utcfromtimestamp(ts)
    
    good-first-issue 
    opened by taleinat 9
  • pin requirements

    pin requirements

    Use pip-tools to pin dependencies. Use pip-compile-multi to automate it. Adding these allows a service like Dependabot to make automatic upgrade PRs and ensures random upgrades won't cause confusing test failures for contributors later. I don't think that's a particular issue for this specific project any time recently, but I want to do this consistently for all the projects.

    To install for dev, you'd now do pip install -e . -r requirements/dev.txt, which pulls in the test and docs requirements as well as tox and pre-commit. (You could skip dev.txt if you have tox and pre-commit installed globally with pipx.) ReadTheDocs is configured to use requirements/docs.txt (it was using docs/requirements.txt which was manually pinning dependencies before). Tox is configured to use requirements/tests.txt.

    opened by davidism 8
  • Add TimedJSONWebSignatureSerializer

    Add TimedJSONWebSignatureSerializer

    Hi,

    this adds a TimedJSONWebSignatureSerializer that makes use of 'exp' as specified in http://self-issued.info/docs/draft-ietf-oauth-json-web-token.html#expDef to encode the expiry time. This makes the expire time self contained so there's no need to pass in a max_age or expires_in when deserializing.

    opened by bracki 8
  • Timestamps: monotonic and higher resolution?

    Timestamps: monotonic and higher resolution?

    Thanks for itsdangerous! It has been a very helpful package thus far. We are currently using it to sign and timestamp one-time tokens and were wondering if adding a lower time resolution as well as monotonic time will help to reduce the risk of token replay attacks and skewed clocks. Thanks!

    opened by c4milo 6
Releases(2.1.2)
  • 2.1.2(Mar 24, 2022)

    • Changes: https://itsdangerous.palletsprojects.com/en/2.1.x/changes/#version-2-1-2
    • Milestone: https://github.com/pallets/itsdangerous/milestone/7?closed=1
    Source code(tar.gz)
    Source code(zip)
  • 2.1.1(Mar 9, 2022)

    • Changes: https://itsdangerous.palletsprojects.com/en/2.1.x/changes/#version-2-1-1
    • Milestone: https://github.com/pallets/itsdangerous/milestone/6?closed=1
    Source code(tar.gz)
    Source code(zip)
  • 2.1.0(Feb 18, 2022)

    • Changes: https://itsdangerous.palletsprojects.com/en/2.1.x/changes/#version-2-1-0
    • Milestone: https://github.com/pallets/itsdangerous/milestone/4
    Source code(tar.gz)
    Source code(zip)
  • 2.0.1(May 18, 2021)

  • 2.0.0(May 12, 2021)

    New major versions of all the core Pallets libraries, including ItsDangerous 2.0, have been released! :tada:

    • Read the announcement on our blog: https://palletsprojects.com/blog/flask-2-0-released/
    • Read the full list of changes: https://itsdangerous.palletsprojects.com/changes/#version-2-0-0
    • Retweet the announcement on Twitter: https://twitter.com/PalletsTeam/status/1392266507296514048
    • Follow our blog, Twitter, or GitHub to see future announcements.

    This represents a significant amount of work, and there are quite a few changes. Be sure to carefully read the changelog, and use tools such as pip-compile and Dependabot to pin your dependencies and control your updates.

    Source code(tar.gz)
    Source code(zip)
  • 2.0.0rc2(Apr 16, 2021)

Our Ping Pong Project of numerical analysis, 2nd year IC B2 INSA Toulouse

Ping Pong Project The objective of this project was to determine the moment of impact of the ball with the ground. To do this, we used different model

0 Jan 02, 2022
Active Transport Analytics Model: A new strategic transport modelling and data visualization framework

{ATAM} Active Transport Analytics Model Active Transport Analytics Model (“ATAM”

ATAM Analytics 2 Dec 21, 2022
Example python package with pybind11 cpp extension

Developing C++ extension in Python using pybind11 This is a summary of the commands used in the tutorial.

55 Sep 04, 2022
Application launcher and environment management

Application launcher and environment management for 21st century games and digital post-production, built with bleeding-rez and Qt.py News Date Releas

10 Nov 03, 2022
Konomi: Kind and Optimized Next brOadcast watching systeM Infrastructure

Konomi 備考・注意事項 現在 α 版で、まだ実験的なプロダクトです。通常利用には耐えないでしょうし、サポートもできません。 安定しているとは到底言いがたい品質ですが、それでも構わない方のみ導入してください。 使い方などの説明も用意できていないため、自力でトラブルに対処できるエンジニアの方以外に

tsukumi 243 Dec 30, 2022
python scripts - mostly automation scripts

python python scripts - mostly automation scripts You can set your environment in various ways bash #!/bin/bash python - locally on remote host #!/bi

Enyi 1 Jan 05, 2022
Simple plug-and-play installer for users who want to LineageOS from stock firmware, or from another custom ROM.

LineageOS for the Teracube 2e Simple plug-and-play installer for users who want to LineageOS from stock firmware, or from another custom ROM. Dependen

Gagan Malvi 5 Mar 31, 2022
little proyect to organize myself, but maybe can help someone else

TaskXT 0.1 Little proyect to organize myself, but maybe can help someone else Idea The main idea is to ogranize you work and stuff to do, but with onl

Gabriel Carmona 4 Oct 03, 2021
an opensourced roblox group finder writen in python 100% free and virus-free

Roblox-Group-Finder an opensourced roblox group finder writen in python 100% free and virus-free note : if you don't want install python or just use w

mollomm1 1 Nov 11, 2021
Control your gtps with gtps-tools!

Note Please give credit to me! Do not try to sell this app, because this app is 100% open source! Do not try to reupload and rename the creator app! S

Jesen N 6 Feb 16, 2022
ASVspoof 2021 Baseline Systems

ASVspoof 2021 Baseline Systems Baseline systems are grouped by task: Speech Deepfake (DF) Logical Access (LA) Physical Access (PA) Please find more de

91 Dec 28, 2022
Um jogo para treinar COO em python

WAR DUCK Este joguinho bem simples tem como objetivo treinar um pouquinho de POO com python. Não é nada muito complexo mas da pra se divertir Como rod

Gabriel Jospin 3 Sep 19, 2021
The first Python 1v1.lol triggerbot working with colors !

1v1.lol TriggerBot Afin d'utiliser mon triggerbot, vous devez activer le plein écran sur 1v1.lol sur votre naviguateur (quelque-soit ce dernier). Vous

Venax 5 Jul 25, 2022
Modelling the 30 salamander problem from `Pure Mathematics` by Martin Liebeck

Salamanders on an island The Problem From A Concise Introduction to Pure Mathematics By Martin Liebeck Critic Ivor Smallbrain is watching the horror m

Faisal Jina 1 Jul 10, 2022
Python-geoarrow - Storing geometry data in Apache Arrow format

geoarrow Storing geometry data in Apache Arrow format Installation $ pip install

Joris Van den Bossche 11 Mar 03, 2022
WATTS provides a set of Python classes that can manage simulation workflows for multiple codes where information is exchanged at a coarse level

WATTS (Workflow and Template Toolkit for Simulation) provides a set of Python classes that can manage simulation workflows for multiple codes where information is exchanged at a coarse level.

13 Dec 23, 2022
A system for assigning and grading notebooks

nbgrader Linux: Windows: Forum: Coverage: Cite: A system for assigning and grading Jupyter notebooks. Documentation can be found on Read the Docs. Hig

Project Jupyter 1.2k Dec 26, 2022
pyinsim is a InSim module for the Python programming language.

PYINSIM pyinsim is a InSim module for the Python programming language. It creates socket connection with LFS and provides many classes, functions and

2 May 12, 2022
Notebook researcher - Notebook researcher with python

notebook_researcher To run the server, you must follow these instructions: At th

4 Sep 02, 2022
Project repository of Apache Airflow, deployed on Docker in Amazon EC2 via GitLab.

Airflow on Docker in EC2 + GitLab's CI/CD Personal project for simple data pipeline using Airflow. Airflow will be installed inside Docker container,

Ammar Chalifah 13 Nov 29, 2022