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)

This is a python package to get wards, districts,cities and provinces in Zimbabwe

Zim-Places Features This is a python package that allows you to search for cities, provinces, and districts in Zimbabwe.Zimbabwe is split into eight p

RONALD KANYEPI 2 Mar 01, 2022
Simple calculator made in python

calculator Uma alculadora simples feita em python CMD, PowerShell, Bash ✔️ Início 💻 apt-get update apt-get upgrade -y apt-get install python git git

Spyware 8 Dec 28, 2021
A shim for the typeshed changes in mypy 0.900

types-all A shim for the typeshed changes in mypy 0.900 installation pip install types-all why --install-types is annoying, this installs all the thin

Anthony Sottile 28 Oct 20, 2022
A simple tool made in Python language

Simple tool Uma simples ferramenta feita 100% em linguagem Python 💻 Requisitos: Python3 instalado em seu dispositivo Clonagem e acesso 📳 git clone h

josh washington 4 Dec 07, 2021
Auto Join Zoom Meeting

Auto-Join-Zoom-Meeting Join a zoom meeting with out filling in meeting id's or passcodes, one button for it all! Setup See attached excel document. MA

JareBear 1 Jan 25, 2022
A place where the most basic, basic of python coding exists

python-basics A place where the most basic, basic of python coding exists As you can see, there are four folders and the best order to read is: appeti

Chuqin 2 Oct 05, 2022
This is the course project of AI3602: Data Mining of SJTU

This is the course project of AI3602: Data Mining of SJTU. Group Members include Jinghao Feng, Mingyang Jiang and Wenzhong Zheng.

2 Jan 13, 2022
Custom component to calculate estimated power consumption of lights and other appliances

Custom component to calculate estimated power consumption of lights and other appliances. Provides easy configuration to get virtual power consumption sensors in Home Assistant for all your devices w

Bram Gerritsen 552 Dec 28, 2022
Hypothesis strategies for generating Python programs, something like CSmith

hypothesmith Hypothesis strategies for generating Python programs, something like CSmith. This is definitely pre-alpha, but if you want to play with i

Zac Hatfield-Dodds 73 Dec 14, 2022
Your copilot to studies and work (Pomodoro-timer, Translate and Notes app)

Copylot Your copilot to studies and work (Pomodoro-timer, Translate and Notes app) Copylot are three applications in one: Pomodoro Translate Notes Cop

Eduardo Mendes 20 Dec 16, 2022
ioztat is a storage load analysis tool for OpenZFS

ioztat is a storage load analysis tool for OpenZFS. It provides iostat-like statistics at an individual dataset/zvol level.

Jim Salter 116 Nov 25, 2022
SQL centered, docker process running game

REQUIREMENTS Linux Docker Python/bash set up image "docker build -t game ." create db container "run my_whatever/game_docker/pdb create" # creating po

1 Jan 11, 2022
A gamey, snakey esoteric programming language

Snak Snak is an esolang based on the classic snake game. Installation You will need python3. To use the visualizer, you will need the curses module. T

David Rutter 3 Oct 10, 2022
Earth-to-orbit ballistic trajectories with atmospheric resistance

Earth-to-orbit ballistic trajectories with atmospheric resistance Overview Space guns are a theoretical technology that reduces the cost of getting bu

1 Dec 03, 2021
Reference python implementation of Chia pool operations for pool operators

This repository provides a sample server written in python, which is meant to server as a basis for a Chia Pool. While this is a fully functional implementation, it requires some work in scalability

Chia Network 451 Dec 13, 2022
Nesse repositório serão armazenados os conteúdos de aula

Lets_Code_DS_Degree_Alunos Nesse repositório serão armazenados os conteúdos de aula Formato das aulas: Notebook de aula já vem comentado para reduzir

Patricia Bongiovanni Catandi 6 Jan 21, 2022
:fishing_pole_and_fish: List of `pre-commit` hooks to ensure the quality of your `dbt` projects.

pre-commit-dbt List of pre-commit hooks to ensure the quality of your dbt projects. BETA NOTICE: This tool is still BETA and may have some bugs, so pl

Offbi 262 Nov 25, 2022
A code to clean and extract a bib file based on keywords.

These are two scripts I use to generate clean bib files. clean_bibfile.py: Removes superfluous fields (which are not included in fields_to_keep.json)

Antoine Allard 4 May 16, 2022
The next generation Canto RSS daemon

Canto Daemon This is the RSS backend for Canto clients. Canto-curses is the default client at: http://github.com/themoken/canto-curses Requirements De

Jack Miller 155 Dec 28, 2022
Stock Monitoring

Stock Monitoring Description It is a stock monitoring script. This repository is still under developing. Getting Started Prerequisites & Installing pi

Sission 1 Feb 03, 2022