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)

Trusted sessions for falcon using itsdangerous.

Falcon signed sessions This project allows you to easily add trusted cookies to falcon, it works by storing a signed cookie in the client's browser us

Ward 1 Feb 8, 2022
Change your Windows background with this program safely & easily!

Background_Changer Table of Contents: About the Program Features Requirements Preview Credits Reach Me See Also About the Program: You can change your

Sina.f 0 Jul 14, 2022
Run python scripts and pass data between multiple python and node processes using this npm module

Run python scripts and pass data between multiple python and node processes using this npm module. process-communication has a event based architecture for interacting with python data and errors inside nodejs.

Tyler Laceby 2 Aug 6, 2021
A python script to run any executable and pass test cases to it's stdin and compare stdout with correct output.

quera_testcase_checker A python script to run any executable and pass test cases to it's stdin and compare stdout with correct output. proper way to u

k3y1 1 Nov 15, 2021
This is the core of the program which takes 5k SYMBOLS and looks back N years to pull in the daily OHLC data of those symbols and saves them to disc.

This is the core of the program which takes 5k SYMBOLS and looks back N years to pull in the daily OHLC data of those symbols and saves them to disc.

Daniel Caine 1 Jan 31, 2022
Python NZ COVID Pass Verifier/Generator

Python NZ COVID Pass Verifier/Generator This is quick proof of concept verifier I coded up in a few hours using various libraries to parse and generat

NZ COVID Pass Community 12 Jan 3, 2023
Random pass word generator made with python. PyQt5 module is used to design GUI.

Differences in this GUI program : Default titlebar removed Custom Minimize,Maximize and Close Buttons Drag & move window from any point Program work l

Dimuth De Zoysa 1 Jan 26, 2022
Compile Binary Ninja's HLIL IR to LLVM, for purposes of compiling it back to a binary again.

Compiles BinaryNinja's HLIL to LLVM Approach Sweep binary for global variables, create them Sweep binary for (used?) external functions, declare those

Kyle Martin 31 Nov 10, 2022
NORETURN is an esoteric programming language, based around the idea of not going back

NORETURN NORETURN is an esoteric programming language, based around the idea of not going back Concept Program coded in noreturn runs over one array,

null 1 Dec 15, 2021
Manipulation OpenAI Gym environments to simulate robots at the STARS lab

liegroups Python implementation of SO2, SE2, SO3, and SE3 matrix Lie groups using numpy or PyTorch. [Documentation] Installation To install, cd into t

STARS Laboratory 259 Dec 11, 2022
Traditionally, there is considerable friction for developers when setting up development environments

This self-led, half-day training will teach participants the patterns and best practices for working with GitHub Codespaces

CSE Labs at Spark 12 Dec 2, 2022
Url-check-migration-python - A python script using Apica API's to migrate URL checks between environments

url-check-migration-python A python script using Apica API's to migrate URL chec

Angelo Aquino 1 Feb 16, 2022
A Pythonic Data Catalog powered by Ray that brings exabyte-level scalability and fast, ACID-compliant, change-data-capture to your big data workloads.

DeltaCAT DeltaCAT is a Pythonic Data Catalog powered by Ray. Its data storage model allows you to define and manage fast, scalable, ACID-compliant dat

null 45 Oct 15, 2022
Data Structures and Algorithms Python - Practice data structures and algorithms in python with few small projects

Data Structures and Algorithms All the essential resources and template code nee

Hesham 13 Dec 1, 2022
Adansons Base is a data management tool that organizes metadata of unstructured data and creates and organizes datasets.

Adansons Base is a data management tool that organizes metadata of unstructured data and creates and organizes datasets. It makes dataset creation more effective and helps find essential insights from training results and improves AI performance.

Adansons Inc 27 Oct 22, 2022
Yunqi Chen 7 Oct 30, 2022
An unofficial python API for trading on the DeGiro platform, with the ability to get real time data and historical data.

DegiroAPI An unofficial API for the trading platform Degiro written in Python with the ability to get real time data and historical data for products.

Jorrick Sleijster 5 Dec 16, 2022
Improve current data preprocessing for FTM's WOB data to analyze Shell and Dutch Governmental contacts.

We're the hackathon leftovers, but we are Too Good To Go ;-). A repo by Lukas Schubotz and Raymon van Dinter. We aim to improve current data preprocessing for FTM's WOB data to analyze Shell and Dutch Governmental contacts.

ASReview hackathon for Follow the Money 5 Dec 9, 2021
Python for downloading model data (HRRR, RAP, GFS, NBM, etc.) from NOMADS, NOAA's Big Data Program partners (Amazon, Google, Microsoft), and the University of Utah Pando Archive System.

Python for downloading model data (HRRR, RAP, GFS, NBM, etc.) from NOMADS, NOAA's Big Data Program partners (Amazon, Google, Microsoft), and the University of Utah Pando Archive System.

Brian Blaylock 194 Jan 2, 2023