ItsDangerous Timed Serializer Tokens

Sign expiring action tokens with itsdangerous, binding purpose and user context so reset links cannot be replayed cross-endpoint.

PythonAuth Jwt

Code

pythonsnippet
39 lines
import hashlib

from itsdangerous import BadSignature, SignatureExpired, URLSafeTimedSerializer

SECRET = 'shared-secret-from-env'
MAX_AGE_SECONDS = 3600


def make_purpose_serializer(secret: str, purpose: str):
    salt = hashlib.sha256(purpose.encode()).hexdigest()[:16]
    return URLSafeTimedSerializer(secret, salt=salt)


reset_serializer = make_purpose_serializer(SECRET, 'password-reset')
verify_serializer = make_purpose_serializer(SECRET, 'email-verify')


def issue_reset_token(user_id: str) -> str:
    return reset_serializer.dumps({'uid': user_id})


def consume_reset_token(token: str) -> str:
    try:
        payload = reset_serializer.loads(token, max_age=MAX_AGE_SECONDS)
    except SignatureExpired:
        raise ValueError('token expired, request a fresh link')
    except BadSignature:
        raise ValueError('token signature invalid')
    return payload['uid']


token = issue_reset_token('user-42')
print('reset accepted:', consume_reset_token(token))

try:
    # 令牌跨用途复用:盐不匹配导致签名校验失败
    verify_serializer.loads(token, max_age=MAX_AGE_SECONDS)
except BadSignature:
    print('cross-purpose replay blocked')

Inside the snippet

Count the functions make_purpose_serializer, issue_reset_token and consume_reset_token as the entire surface area of ItsDangerous Timed Serializer Tokens.

From itsdangerous it pulls BadSignature, SignatureExpired, URLSafeTimedSerializer — the imports name exactly which library surface the snippet touches. A ValueError is raised inside an except block, so it is conditional on that failure being handled in the first place.

What to watch for

  • Requires itsdangerous as a package; the snippet will not run without it.

Using it

The primary signature is def make_purpose_serializer(secret: str, purpose: str)

Look for the reset accepted:, cross-purpose replay blocked prefixes when the file runs; they tie each line to its step.

Import make_purpose_serializer from the file and call it — the rest of the code is implementation detail.

Key statements

def make_purpose_serializer(secret: str, purpose: str):
    salt = hashlib.sha256(purpose.encode()).hexdigest()[:16]
    return URLSafeTimedSerializer(secret, salt=salt)
def issue_reset_token(user_id: str) -> str:
    return reset_serializer.dumps({'uid': user_id})
except SignatureExpired:
    raise ValueError('token expired, request a fresh link')

Interactive Tools for This Topic

FAQ

When is the exception raised?
Inside an `except` handler — the `ValueError` fires only while that failure type is already being handled, not on its own trigger.
Are there third-party dependencies?
`itsdangerous` — install it with the package manager before running.