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)

A general illumination correction method for optical microscopy.

CIDRE About CIDRE is a retrospective illumination correction method for optical microscopy. It is designed to correct collections of images by buildin

Kevin Smith 31 Sep 07, 2022
Fast Base64 encoding/decoding in Python

Fast Base64 implementation This project is a wrapper on libbase64. It aims to provide a fast base64 implementation for base64 encoding/decoding. Insta

Matthieu Darbois 96 Dec 26, 2022
Waydroid is a container-based approach to boot a full Android system on a regular GNU/Linux system like Ubuntu.

Waydroid is a container-based approach to boot a full Android system on a regular GNU/Linux system like Ubuntu.

WayDroid 4.7k Jan 08, 2023
Fully cross-platform toolkit (and library!) for MachO+Obj-C editing/analysis

fully cross-platform toolkit (and library!) for MachO+Obj-C editing/analysis. Includes a cli kit, a curses GUI, ObjC header dumping, and much more.

cynder 301 Dec 28, 2022
BDD base project: Python + Behave

BDD base project: Python + Behave Basic example of using Python with Behave (BDD). This Gherkin example includes: Basic Scenario Scenario Outline Tagg

eccanto 1 Dec 08, 2021
Create VSCode Extensions with python

About Create vscode extensions with python. Installation Stable version: pip install vscode-ext Why use this? Why should you use this for building VSc

Swas.py 134 Jan 07, 2023
A script where you execute a script that generates a base project for your gdextension

GDExtension Project Creator this is a script (currently only for linux) where you execute a script that generates a base project for your gdextension,

Unknown 11 Nov 17, 2022
Sudoku solver using backtracking

Sudoku solver Sudoku solver using backtracking Basically in sudoku, we want to be able to solve a sudoku puzzle given an input like this, which repres

Kylie 99 Jan 07, 2023
This is the Halloween edition of my Flask Greeting App - HAPPY HALLOWEEEN EVERYONE! :)

HalloweenGreetingApp HAPPY HALLOWEEN EVERYONE! :) This is the Halloween Edition of my Flask Greeting App! Please note, this application is mean to be

Mariya 2 Feb 04, 2022
Яндекс тренировки по алгоритмам. Июнь 2021

Young&&Yandex Тренировки по алгоритмам Если вы хотите попасть на летнюю стажировку в Яндекс, но пока не уверены в своих силах, приходите на наши трени

Podlevskiy Viktor 6 Sep 03, 2021
Darkflame Universe Account Manager

Darkflame Universe Account Manager This is a quick and simple web application intended for account creation and management for a DLU instance created

31 Nov 29, 2022
Python Project For Beginner

Basic-Vitrual-AI-Assistant Python Project For Beginner Hey There, I had manipulated Selenium WebDriver to make this assistant. I hope, It will be help

Maruf Billah 13 Dec 12, 2022
Devil - Very Semple Auto Filter V1 Bot

Devil Very Semple Auto Filter V1 Bot

2 Jun 27, 2022
A collection of full-stack resources for programmers.

A collection of full-stack resources for programmers.

Charles-Axel Dein 22.3k Dec 30, 2022
DRF magic links

drf-magic-links Installation pip install drf-magic-links Add URL patterns # urls.py

Dmitry Kalinin 1 Nov 07, 2021
This repository contains Python games that I've worked on. You'll learn how to create python games with AI. I try to focus on creating board games without GUI in Jupyter-notebook.

92_Python_Games 🎮 Introduction 👋 This repository contains Python games that I've worked on. You'll learn how to create python games with AI. I try t

Milaan Parmar / Милан пармар / _米兰 帕尔马 166 Jan 01, 2023
Packaging tools for shanty services.

parcel Packaging tools for shanty services. What? Services are docker containers deployed by shanty on a hosting appliance. Each service consists of t

0 Jan 20, 2022
Multitrack exporter for OP-Z

Underbridge for OP-Z Multitrack exporter Description Exports patterns and projects individual audio tracks to seperate folders for use in your DAW. Py

Thomas Herrmann 71 Dec 25, 2022
Streamlit component to display topics from Streamlit's community forum related to any exception.

streamlit-forum Streamlit component to display topics from Streamlit's community forum related to any exception. Installation pip install streamlit-fo

Snehan Kekre 7 Jul 15, 2022
This is an example manipulation package of for a robot manipulator based on Drake with ROS2.

This is an example manipulation package of for a robot manipulator based on Drake with ROS2.

Sotaro Katayama 1 Oct 21, 2021