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)

Backend Interview Challenge

Inspect HOA backend challenge This is a simple flask repository with some endpoints and requires a few more endpoints. It follows a simple MVP (model-

1 Jan 20, 2022
This application demonstrates IoTVAS device discovery and security assessment API integration with the Rapid7 InsightVM.

Introduction This repository hosts a sample application that demonstrates integrating Firmalyzer's IoTVAS API with the Rapid7 InsightVM platform. This

Firmalyzer BV 4 Nov 09, 2022
Penelope Shell Handler

penelope Penelope is an advanced shell handler. Its main aim is to replace netcat as shell catcher during exploiting RCE vulnerabilities. It works on

293 Dec 30, 2022
People tracker on the Internet: OSINT analysis and research tool by Jose Pino

trape (stable) v2.0 People tracker on the Internet: Learn to track the world, to avoid being traced. Trape is an OSINT analysis and research tool, whi

Jose Pino 7.3k Dec 30, 2022
A Powerful Tool For Making Combo List(All possible modes)

ComboMaker A Powerful Tool For Making Combo List Introduction Check out all possible Combo list build modes with this tool =) How to Install Open the

MasterBurnt 7 Jan 07, 2023
A simple Programming Language

R.S.O.C. A custom built programming language About The Project R.S.O.C. is a custom built programming language very similar to a low-level 8085 progra

Ravi Maurya 17 Sep 13, 2022
NewsBlur is a personal news reader bringing people together to talk about the world.

NewsBlur NewsBlur is a personal news reader bringing people together to talk about the world.

Samuel Clay 6.2k Dec 29, 2022
Run unpatched binaries on Nix/NixOS

Run unpatched binaries on Nix/NixOS

Thiago Kenji Okada 160 Jan 08, 2023
Tools for teachers and students using nng (Natural Number Game)

nngtools Usage Place your nngsave.json to the directory in which you want to extract the level files. Place nngmap.json on the same directory. Run nng

Thanos Tsouanas 1 Dec 12, 2021
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
NGEBUG is a tool that sends viruses to victims

Ngebug NGEBUG adalah tools pengirim virus ke korban NGEBUG adalah tools virus terbaru yang berasal dari rusia Informasi lengkap ada didalam tools Run

Profesor Acc 3 Dec 13, 2021
Dockernized ZeroTierOne controller with zero-ui web interface.

docker-zerotier-controller Dockernized ZeroTierOne controller with zero-ui web interface. 中文讨论 Customize ZeroTierOne's controller planets Modify patch

sbilly 209 Jan 04, 2023
JARVIS PC Assistant is an assisting program to make your computer easier to use

JARVIS-PC-Assistant JARVIS PC Assistant is an assisting program to make your computer easier to use Welcome to the J.A.R.V.I.S. PC Assistant help file

Dasun Nethsara 2 Dec 02, 2022
GEGVL: Google Earth Based Geoscience Video Library

Google Earth Based Geoscience Video Library is transforming to Server Based. The

3 Feb 11, 2022
The Doodle Master seeks to turn your UI mockups into real code.

Doodle Master The Doodle Master seeks to turn your UI mockups into real code. Currently this repository just serves to demonstrate a Proof Of Concept

Karanbir Chahal 2.4k Dec 09, 2022
Openfe - Alchemical free energy calculations for the masses

The Open Free Energy library Alchemical free energy calculations for the masses.

33 Dec 22, 2022
This is a pretty basic but relatively nice looking Python Pomodoro Timer.

Python Pomodoro-Timer This is a pretty basic but relatively nice looking Pomodoro Timer. Currently its set to a very basic mode, but the funcationalit

EmmHarris 2 Oct 18, 2021
This Python3 script will monitor Upwork RSS feed and then email you the results.

Upwork RSS Parser This Python3 script will monitor Upwork RSS feed and then email you the results. Table of Contents General Info Technologies Used Fe

Chris 5 Nov 29, 2021
inverted pendulum fuzzy control python code (python 2.7.18)

inverted-pendulum-fuzzy-control- inverted pendulum fuzzy control python code (python 2.7.18) We have 3 general functions for 3 main steps: fuzzificati

arian mottaghi 4 May 23, 2022
Path of Exile Vendor Recipe Tracker (Chaos/Regal orb)

Path of Exile Vendor Trade Tracker Are you tired of manually keeping track of collected and missing items for farming Chaos or Regal Orbs in PoE? Me t

1 Nov 09, 2021