### Base64 Decoding Example (Python) Source: https://context7.com/pallets/itsdangerous/llms.txt Demonstrates a basic base64 decoding operation. This snippet shows how to decode a base64 encoded byte string using a hypothetical `base64_decode` function, which is assumed to be available in the context. The output is the original byte string. ```python encoded_no_padding = b'aGVsbG8' decoded = base64_decode(encoded_no_padding) print(decoded) # b'hello' ``` -------------------------------- ### Implement Custom Signing Algorithms with Itsdangerous Source: https://context7.com/pallets/itsdangerous/llms.txt Shows how to implement and use custom signature generation algorithms with itsdangerous. It includes an example of a custom SHA256-based algorithm and a no-operation algorithm for testing purposes. ```python from itsdangerous import Signer, SigningAlgorithm, NoneAlgorithm import hmac # Custom algorithm implementation class CustomAlgorithm(SigningAlgorithm): def get_signature(self, key, value): # Custom signature logic return hmac.new(key, value, 'sha256').digest() # Use custom algorithm signer = Signer('secret-key', algorithm=CustomAlgorithm()) signed = signer.sign('my data') verified = signer.unsign(signed) print(verified) # b'my data' # No-op algorithm (for testing/development) insecure_signer = Signer('secret-key', algorithm=NoneAlgorithm()) signed = insecure_signer.sign('data') print(signed) # b'data.' (no signature) ``` -------------------------------- ### Custom Serialization Formats with Serializer Source: https://context7.com/pallets/itsdangerous/llms.txt Explains how to configure the `Serializer` to use alternative serialization formats beyond JSON, such as `pickle` or `msgpack`. This allows for the secure transmission of more complex Python objects. The example demonstrates using `pickle` to serialize and deserialize a custom class instance, ensuring data integrity. ```python import pickle from itsdangerous import Serializer # Use pickle for complex Python objects class User: def __init__(self, id, name): self.id = id self.name = name pickle_serializer = Serializer( secret_key='secret-key', serializer=pickle ) user = User(42, 'Alice') token = pickle_serializer.dumps(user) restored_user = pickle_serializer.loads(token) print(f'{restored_user.id}: {restored_user.name}') # 42: Alice ``` -------------------------------- ### Handle Exceptions in Itsdangerous Signature and Payload Operations Source: https://context7.com/pallets/itsdangerous/llms.txt Provides examples of how to handle various exceptions raised by itsdangerous during token loading, including signature verification failures, expired signatures, and payload deserialization errors. It covers `BadSignature`, `SignatureExpired`, `BadPayload`, and the general `BadData` exception. ```python from itsdangerous import ( URLSafeTimedSerializer, BadSignature, SignatureExpired, BadPayload, BadData ) s = URLSafeTimedSerializer('secret-key') # BadSignature - signature verification failed try: s.loads('tampered.data.here') except BadSignature as e: print(f'Error: {e.message}') print(f'Payload (if available): {e.payload}') # SignatureExpired - timestamp exceeded max_age try: # Simulate an old token old_token = s.dumps({'id': 42}) # To test, you would need to manually create a token with an old timestamp # or mock time. For demonstration, assume 'old_token' is expired. s.loads(old_token, max_age=1) except SignatureExpired as e: print(f'Expired at: {e.date_signed}') print(f'Payload: {e.payload}') # Still accessible # BadPayload - deserialization failed try: corrupted = s.make_signer().sign(b'not-valid-json') s.loads(corrupted) except BadPayload as e: print(f'Error: {e.message}') print(f'Original error: {e.original_error}') # Catch all itsdangerous errors try: # Assuming untrusted_token is defined elsewhere and potentially invalid untrusted_token = 'potentially-invalid-token' s.loads(untrusted_token, max_age=3600) except BadData as e: # Handles BadSignature, BadPayload, and subclasses print(f'Invalid data: {e.message}') ``` -------------------------------- ### itsdangerous Signer Class Constructor with All Parameters Source: https://github.com/pallets/itsdangerous/blob/main/docs/signer.md Documents the complete Signer class constructor with all available parameters including secret key, salt, separator, key derivation method, digest method, and algorithm. Shows how to configure the signer for different security requirements and use cases, including support for key rotation through a list of secret keys. ```python from itsdangerous import Signer # Basic usage s = Signer("secret-key") # Advanced usage with all parameters s = Signer( secret_key="my-secret-key", salt=b'itsdangerous.Signer', sep=b'.', key_derivation='django-concat', digest_method=None, algorithm=None ) ``` -------------------------------- ### Basic String Signing and Validation with itsdangerous Source: https://github.com/pallets/itsdangerous/blob/main/docs/signer.md Demonstrates the core functionality of signing strings with a secret key and validating signatures. Shows how to create a Signer instance, sign a string, and unsign it to verify the value hasn't been tampered with. Includes handling of Unicode strings which are automatically encoded to UTF-8. ```python from itsdangerous import Signer s = Signer("secret-key") s.sign("my string") b'my string.wh6tMHxLgJqB6oY1uT73iMlyrOA' ``` -------------------------------- ### itsdangerous.serializer.Serializer Initialization Source: https://github.com/pallets/itsdangerous/blob/main/docs/serializer.md Initializes the Serializer with a secret key, salt, and optional serializer and signer configurations. The secret key is crucial for security, and the salt adds an extra layer of protection. Various serialization and signing strategies can be employed. ```python from itsdangerous.serializer import Serializer # Example with default configurations s = Serializer('my-secret-key') # Example with custom salt and JSON serializer from itsdangerous.json import JSONSerializer s_custom = Serializer('another-secret-key', salt='my-salt', serializer=JSONSerializer()) # Example with custom signer from itsdangerous.signer import Signer class MySigner(Signer): pass s_custom_signer = Serializer('key', signer=MySigner) ``` -------------------------------- ### Create and Load Tokens Safely with Itsdangerous Source: https://context7.com/pallets/itsdangerous/llms.txt Demonstrates the basic usage of itsdangerous for creating signed tokens and safely loading them. It shows how to handle valid, tampered, and corrupted tokens, highlighting the security implications of each. ```python from itsdangerous import Serializer s = Serializer('secret-key') # Create valid token valid_token = s.dumps({'user_id': 42}) # Load safely returns (signature_valid, payload) is_valid, data = s.loads_unsafe(valid_token) print(f'Valid: {is_valid}') # True print(f'Data: {data}') # {'user_id': 42} # Tampered token tampered = valid_token[:-5] + 'XXXXX' is_valid, data = s.loads_unsafe(tampered) print(f'Valid: {is_valid}') # False print(f'Data: {data}') # {'user_id': 42} (payload still readable) # Corrupted payload corrupted = s.make_signer().sign(b'invalid-json') is_valid, data = s.loads_unsafe(corrupted) print(f'Valid: {is_valid}') # True (signature is valid) print(f'Data: {data}') # None (payload can't be deserialized) # WARNING: Only use for debugging. Never trust unsigned data. ``` -------------------------------- ### URLSafeSerializer Initialization Source: https://github.com/pallets/itsdangerous/blob/main/docs/url_safe.md Initializes the URLSafeSerializer with a secret key, optional salt, serializer, and signer configurations. The secret_key is essential for signing tokens, while salt helps in isolating tokens. The serializer and signer parameters allow for customization of the serialization and signing mechanisms. ```python from itsdangerous.url_safe import URLSafeSerializer signer = URLSafeSerializer('my-secret-key') ``` -------------------------------- ### Loading Secret Key from Environment in Python Source: https://github.com/pallets/itsdangerous/blob/main/docs/concepts.md Retrieves a secret key from an environment variable and initializes a Serializer for signing data. Purpose: securely configure signing without hardcoding keys. Dependencies: itsdangerous and os modules. Inputs: SECRET_KEY environment variable. Outputs: Serializer instance. Limitations: Requires the key to be set externally; invalid if not present. ```python import os from itsdangerous.serializer import Serializer SECRET_KEY = os.environ.get("SECRET_KEY") s = Serializer(SECRET_KEY) ``` ```bash $ export SECRET_KEY="base64 encoded random bytes" $ python application.py ``` -------------------------------- ### Implementing Key Rotation with Signer Source: https://context7.com/pallets/itsdangerous/llms.txt Shows how to configure the `Signer` to support multiple secret keys for seamless key rotation in production environments. It explains how to sign with the newest key and how the signer can verify signatures made with older keys, ensuring backward compatibility during rotation. This is crucial for maintaining security without disrupting existing signed data. ```python from itsdangerous import Signer # Sign with the newest key signer = Signer(['old-key-1', 'old-key-2', 'current-key']) signed = signer.sign('my data') # Verification tries all keys (newest to oldest) print(signer.unsign(signed)) # b'my data' # Old signatures remain valid old_signer = Signer('old-key-1') old_signed = old_signer.sign('legacy data') # New signer can still verify old signatures print(signer.unsign(old_signed)) # b'legacy data' # Access secret keys print(signer.secret_key) # b'current-key' (newest) print(signer.secret_keys) # [b'old-key-1', b'old-key-2', b'current-key'] ``` -------------------------------- ### Using Salts for Context-Specific Signing with URLSafeSerializer Source: https://github.com/pallets/itsdangerous/blob/main/docs/concepts.md Creates serializers with unique salts to sign data for different contexts, preventing token reuse. Purpose: distinguish signatures for actions like user activation or upgrades. Dependencies: itsdangerous.url_safe module. Inputs: secret key, salt, data (e.g., user ID). Outputs: URL-safe signed string. Limitations: Mismatched salts cause validation failure; salts must be consistent within contexts. ```python from itsdangerous.url_safe import URLSafeSerializer s1 = URLSafeSerializer("secret-key", salt="activate") s1.dumps(42) # 'NDI.MHQqszw6Wc81wOBQszCrEE_RlzY' s2 = URLSafeSerializer("secret-key", salt="upgrade") s2.dumps(42) # 'NDI.c0MpsD6gzpilOAeUPra3NShPXsE' # s2.loads(s1.dumps(42)) raises BadSignature: Signature does not match s2.loads(s2.dumps(42)) # 42 ``` -------------------------------- ### URLSafeTimedSerializer: Loading and Dumping Data Source: https://github.com/pallets/itsdangerous/blob/main/docs/url_safe.md Demonstrates how to serialize (dump) data into a URL-safe string and deserialize (load) it back, including time-based validation. The `dumps` method creates the signed string, while `loads` verifies and decodes it. ```python from itsdangerous.url_safe import URLSafeTimedSerializer serializer = URLSafeTimedSerializer('my-secret-key') # Dump data into a URL-safe string data_to_serialize = {'user_id': 123, 'username': 'testuser'} serialized_data = serializer.dumps(data_to_serialize) print(f"Serialized Data: {serialized_data}") # Load data back, verifying signature and timestamp try: loaded_data = serializer.loads(serialized_data) print(f"Loaded Data: {loaded_data}") except Exception as e: print(f"Error loading data: {e}") # Example of loading with a maximum age (e.g., 1 hour) try: # Assuming 'serialized_data' is from a previous dump loaded_data_max_age = serializer.loads(serialized_data, max_age=3600) print(f"Loaded Data (max_age=3600): {loaded_data_max_age}") except Exception as e: print(f"Error loading data with max_age: {e}") ``` -------------------------------- ### Initialize TimedSerializer in Python Source: https://github.com/pallets/itsdangerous/blob/main/docs/timed.md This snippet shows the constructor for the TimedSerializer class. It initializes the serializer with various parameters including secret_key, salt, serializer, serializer_kwargs, signer, signer_kwargs, and fallback_signers. These parameters allow customization of the serialization and signing process. ```python class itsdangerous.timed.TimedSerializer(secret_key: str | bytes | Iterable[str] | Iterable[bytes], salt: str | bytes | None = b'itsdangerous', serializer: _PDataSerializer[bytes], serializer_kwargs: dict[str, Any] | None = None, signer: type[Signer] | None = None, signer_kwargs: dict[str, Any] | None = None, fallback_signers: list[dict[str, Any] | tuple[type[Signer], dict[str, Any]] | type[Signer]] | None = None) ``` -------------------------------- ### Basic String Signing and Verification with Signer Source: https://context7.com/pallets/itsdangerous/llms.txt Demonstrates how to sign, verify, and unsign strings using the `Signer` class. It shows the process of creating a signer, signing data, and handling successful and failed verification attempts. This is useful for ensuring data integrity when transmitting sensitive information. ```python from itsdangerous import Signer, BadSignature # Create a signer with a secret key signer = Signer('my-secret-key') # Sign a string signed = signer.sign('my data') print(signed) # b'my data.GxOmv75FTe2hqKJU9KKJ9KJGVuM' # Verify and unsign try: original = signer.unsign(signed) print(original) # b'my data' except BadSignature: print('Signature verification failed') # Validate without unsigning is_valid = signer.validate(signed) print(is_valid) # True # Tampered data fails validation tampered = b'tampered data.GxOmv75FTe2hqKJU9KKJ9KJGVuM' print(signer.validate(tampered)) # False ``` -------------------------------- ### Customizing Signer Configuration Source: https://context7.com/pallets/itsdangerous/llms.txt Illustrates how to customize the `Signer` class for various security and functional needs. This includes specifying different digest methods (like SHA-256), key derivation strategies, custom separators, and using salts for distinct signing contexts. These configurations enhance security and flexibility for different use cases. ```python import hashlib from itsdangerous import Signer # Use SHA-256 instead of default SHA-1 signer = Signer( secret_key='my-secret', digest_method=hashlib.sha256 ) # Different key derivation methods signer_hmac = Signer( secret_key='my-secret', key_derivation='hmac' ) signer_concat = Signer( secret_key='my-secret', key_derivation='concat' ) # Custom separator (default is '.') signer_custom = Signer( secret_key='my-secret', sep=':' ) signed = signer_custom.sign('data') print(signed) # b'data:Xy8f...' # Use salt for different signing contexts cookie_signer = Signer('my-secret', salt='cookie-signing') email_signer = Signer('my-secret', salt='email-verification') ``` -------------------------------- ### URLSafeTimedSerializer Initialization Source: https://github.com/pallets/itsdangerous/blob/main/docs/url_safe.md Initializes the URLSafeTimedSerializer with a secret key, salt, and optional serializer and signer configurations. The secret key is crucial for signing and verifying data. ```python from itsdangerous.url_safe import URLSafeTimedSerializer # Basic initialization with secret key serializer = URLSafeTimedSerializer('my-secret-key') # Initialization with custom salt and serializer serializer_custom = URLSafeTimedSerializer( secret_key='another-secret-key', salt='my-custom-salt', serializer=None # Using default JSON serializer ) # Initialization with signer and fallback signers from itsdangerous.signer import Signer signer_instance = Signer('my-secret-key') serializer_with_signer = URLSafeTimedSerializer( secret_key='my-secret-key', signer=Signer, signer_kwargs={'key_derivation': 'django-hmac'} ) ``` -------------------------------- ### JSON Serialization and Signing with Serializer Source: https://context7.com/pallets/itsdangerous/llms.txt Demonstrates how to use the `Serializer` class to serialize Python objects into JSON, sign them, and then deserialize and verify them. This method is ideal for passing structured data, such as user information or application state, securely. It also covers handling invalid signatures and using salts for different data types. ```python from itsdangerous import Serializer, BadSignature # Create serializer s = Serializer('secret-key') # Serialize and sign objects token = s.dumps({'user_id': 42, 'username': 'alice'}) print(token) # '{"user_id":42,"username":"alice"}.C5R...' # Deserialize and verify try: data = s.loads(token) print(data) # {'user_id': 42, 'username': 'alice'} except BadSignature as e: print(f'Invalid signature: {e.message}') print(f'Payload was: {e.payload}') # Use different salt for different purposes user_serializer = s.dumps({'id': 42}, salt='user-auth') email_serializer = s.dumps({'email': 'test@example.com'}, salt='email-verify') # File I/O operations with open('token.txt', 'w') as f: s.dump({'user_id': 42}, f) with open('token.txt', 'r') as f: data = s.load(f) print(data) # {'user_id': 42} ``` -------------------------------- ### Utilize Encoding Utilities in Itsdangerous Source: https://context7.com/pallets/itsdangerous/llms.txt Demonstrates the use of low-level encoding and decoding functions provided by itsdangerous, including converting strings to bytes using `want_bytes` and performing URL-safe base64 encoding and decoding. ```python from itsdangerous import ( want_bytes, base64_encode, base64_decode ) # Convert strings to bytes data = want_bytes('hello') print(data) # b'hello' data = want_bytes(b'already bytes') print(data) # b'already bytes' # URL-safe base64 encoding (no padding) encoded = base64_encode('hello world') print(encoded) # b'aGVsbG8gd29ybGQ' decoded = base64_decode(encoded) print(decoded) # b'hello world' ``` -------------------------------- ### URLSafeSerializer Dump and Load Source: https://github.com/pallets/itsdangerous/blob/main/docs/url_safe.md Demonstrates how to use URLSafeSerializer to dump data into a URL-safe string and load it back. The dump method encodes the data, and the load method decodes and verifies the signature. This is useful for passing data securely in URLs. ```python from itsdangerous.url_safe import URLSafeSerializer signer = URLSafeSerializer('my-secret-key') data = {'user_id': 123, 'role': 'admin'} # Dump data to a URL-safe string token = signer.dumps(data) print(f"Serialized token: {token}") # Load data back from the token loaded_data = signer.loads(token) print(f"Deserialized data: {loaded_data}") ``` -------------------------------- ### Implement Custom Serializer in Python Source: https://context7.com/pallets/itsdangerous/llms.txt Demonstrates creating a custom serializer class with dumps and loads methods for ItsDangerous. Requires ItsDangerous library; inputs are objects to serialize, outputs are serialized bytes. Limitations include security risks from using eval() in loads method. ```python # Custom serializer (must have dumps/loads methods) class CustomSerializer: def dumps(self, obj): return str(obj).encode('utf-8') def loads(self, data): return eval(data.decode('utf-8')) custom = Serializer( secret_key='secret-key', serializer=CustomSerializer() ) ``` -------------------------------- ### Support Legacy Signatures with Fallback Signers in Itsdangerous Source: https://context7.com/pallets/itsdangerous/llms.txt Illustrates how to configure itsdangerous Serializer to support legacy signature formats during data migration. It demonstrates setting up fallback signers with different secret keys, digest methods, and salts. ```python from itsdangerous import Serializer import hashlib # Current configuration current_serializer = Serializer('new-secret-key') # Support old signature formats serializer = Serializer( secret_key='new-secret-key', fallback_signers=[ # Old key with SHA-256 {'secret_key': 'old-secret-key', 'digest_method': hashlib.sha256}, # Very old key with different salt {'secret_key': 'legacy-key', 'salt': 'old-salt'}, ] ) # Can verify tokens signed with old configuration old_token = Serializer('old-secret-key', digest_method=hashlib.sha256).dumps({'id': 42}) data = serializer.loads(old_token) print(data) # {'id': 42} # New tokens use current configuration new_token = serializer.dumps({'id': 42}) ``` -------------------------------- ### Generating Random Secret Key Using os.urandom Source: https://github.com/pallets/itsdangerous/blob/main/docs/concepts.md Generates a random secret key using Python's os.urandom for secure initialization. Purpose: create a strong, unique secret key. Dependencies: os module. Inputs: desired length (e.g., 16 bytes). Outputs: hexadecimal string representation. Limitations: Output is random and must be stored securely. ```bash $ python3 -c 'import os; print(os.urandom(16).hex())' ``` -------------------------------- ### TimedSerializer Initialization (Python) Source: https://github.com/pallets/itsdangerous/blob/main/docs/timed.md Initializes a TimedSerializer object. This class is used for signing and serializing data with a time-based expiration. It accepts a secret key, salt, and optional serializer and signer configurations. ```python from itsdangerous.timed import TimedSerializer token_serializer = TimedSerializer('my-secret-key') ``` -------------------------------- ### Configuring Fallback Signers for Compatibility (Python) Source: https://github.com/pallets/itsdangerous/blob/main/docs/serializer.md Fallback signers allow verifying old signatures with different parameters, like digest methods, during upgrades. Requires hashlib for digest functions and itsdangerous for Serializer. New data uses primary signer; old data tries fallbacks in order until successful. ```python import hashlib s = Serializer( signer_kwargs={"digest_method": hashlib.sha512}, fallback_signers=[{"digest_method": hashlib.sha1}] ) ``` -------------------------------- ### Enable Unsafe Loading for Debugging in Python Source: https://context7.com/pallets/itsdangerous/llms.txt Shows how to inspect payloads in Serializer without verification for debugging. Requires ItsDangerous; useful for development but not production due to security risks. Takes signed data as input, outputs payload without checks. ```python from itsdangerous import Serializer s = Serializer('secret-key') ``` -------------------------------- ### Perform URL-Safe Serialization in Python Source: https://context7.com/pallets/itsdangerous/llms.txt Creates compact, URL-safe tokens with automatic compression using URLSafeSerializer. Uses ItsDangerous; handles JSON data, outputs URL-friendly strings. Automatically compresses large data, but small data remains uncompressed for efficiency. ```python from itsdangerous import URLSafeSerializer # Create URL-safe serializer s = URLSafeSerializer('secret-key') # Generates tokens safe for URLs (no padding, uses -_ instead of +/) token = s.dumps({'user_id': 42, 'permissions': ['read', 'write']}) print(token) # 'eyJ1c2VyX2lkIjo0Miwi...' (safe for URLs) # Can be used in query strings url = f'https://example.com/verify?token={token}' # Deserialize from token data = s.loads(token) print(data) # {'user_id': 42, 'permissions': ['read', 'write']} # Large data is automatically compressed large_data = {'key': 'x' * 1000} compressed_token = s.dumps(large_data) print(f'Compressed: {len(compressed_token)} bytes') # Compression marker (leading .) indicates zlib compression was used # Small data is not compressed as it would increase size ``` -------------------------------- ### Basic Data Serialization and Deserialization with Serializer (Python) Source: https://github.com/pallets/itsdangerous/blob/main/docs/serializer.md The Serializer class serializes Python objects to JSON and signs them with a secret key for tamper-proof transmission. It depends on the itsdangerous library and Python's json module. Inputs are serializable objects; outputs are signed byte strings for dumps and original objects for loads if signature is valid. ```python from itsdangerous.serializer import Serializer s = Serializer("secret-key") s.dumps([1, 2, 3, 4]) s.loads(b'[1, 2, 3, 4].r7R9RhGgDPvvWl3iNzLuIIfELmo') ``` -------------------------------- ### itsdangerous.timed.TimedSerializer Source: https://github.com/pallets/itsdangerous/blob/main/docs/timed.md Initializes a TimedSerializer. This serializer uses TimestampSigner by default for time-based security. ```APIDOC ## itsdangerous.timed.TimedSerializer ### Description Initializes a TimedSerializer. This serializer uses TimestampSigner by default for time-based security. ### Method Constructor ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **secret_key** (str | bytes | Iterable[str] | Iterable[bytes]) - Required - The secret key used for signing. - **salt** (str | bytes | None) - Optional - A salt to add to the signing key. - **serializer** (_PDataSerializer[_TSerialized]) - Optional - The serializer to use for data serialization (e.g., JSON). - **serializer_kwargs** (dict[str, Any] | None) - Optional - Keyword arguments for the serializer. - **signer** (type[Signer] | None) - Optional - The signer class to use (defaults to TimestampSigner). - **signer_kwargs** (dict[str, Any] | None) - Optional - Keyword arguments for the signer. - **fallback_signers** (list[dict[str, Any] | tuple[type[Signer], dict[str, Any]] | type[Signer]] | None) - Optional - A list of fallback signers. ### Request Example ```python from itsdangerous.timed import TimedSerializer s = TimedSerializer('my-secret-key') data = {'user_id': 123} serialized_data = s.dumps(data) print(serialized_data) ``` ### Response #### Success Response (Initialization) An instance of TimedSerializer. #### Response Example ```json { "message": "TimedSerializer initialized successfully" } ``` ``` -------------------------------- ### Signature Validation and Error Handling in itsdangerous Source: https://github.com/pallets/itsdangerous/blob/main/docs/signer.md Shows how to handle signature validation failures when the signed data has been modified. Demonstrates the BadSignature exception that is raised when the signature doesn't match, which is crucial for detecting tampered data in security-sensitive applications. ```python s.unsign(b"my string.wh6tMHxLgJqB6oY1uT73iMlyrOA") b'my string' ``` -------------------------------- ### Create and sign a timestamped value in Python Source: https://github.com/pallets/itsdangerous/blob/main/docs/timed.md Demonstrates how to use TimestampSigner to sign a value with a timestamp. Requires the itsdangerous library. The signed value includes the current time. ```python from itsdangerous import TimestampSigner s = TimestampSigner('secret-key') string = s.sign('foo') ``` -------------------------------- ### Serialize Data URL-Safe in Python Source: https://github.com/pallets/itsdangerous/blob/main/docs/url_safe.md Demonstrates usage of URLSafeSerializer to encode and decode data securely for URLs. Depends on the itsdangerous library. Inputs include data to serialize and a secret key; outputs are URL-safe signed strings. Note that decoding requires the same secret key for verification. ```python from itsdangerous.url_safe import URLSafeSerializer s = URLSafeSerializer("secret-key") s.dumps([1, 2, 3, 4]) 'WzEsMiwzLDRd.wSPHqC0gR7VUqivlSukJ0IeTDgo' s.loads("WzEsMiwzLDRd.wSPHqC0gR7VUqivlSukJ0IeTDgo") [1, 2, 3, 4] ``` -------------------------------- ### Create Time-Based Signatures in Python Source: https://context7.com/pallets/itsdangerous/llms.txt Shows how to use TimestampSigner for creating and verifying expiring signatures. Depends on ItsDangerous and time modules; takes data to sign and optional max_age, returns signed data or errors. Useful for temporary validations but requires careful handling of expiration times. ```python from itsdangerous import TimestampSigner, SignatureExpired, BadSignature import time # Create timestamp signer signer = TimestampSigner('secret-key') # Sign with timestamp signed = signer.sign('my data') print(signed) # b'my data.XyZ123.AbC456' # Unsign with max_age (in seconds) try: data = signer.unsign(signed, max_age=3600) # Valid for 1 hour print(data) # b'my data' except SignatureExpired as e: print(f'Signature expired') print(f'Signed at: {e.date_signed}') print(f'Payload: {e.payload}') except BadSignature: print('Invalid signature') # Get timestamp when unsigning data, timestamp = signer.unsign(signed, return_timestamp=True) print(f'Data: {data}') # b'my data' print(f'Signed at: {timestamp}') # 2025-01-15 10:30:45.123456+00:00 # Test expiration time.sleep(2) try: signer.unsign(signed, max_age=1) # Expires after 1 second except SignatureExpired: print('Signature is too old') ``` -------------------------------- ### Itsdangerous Serializer Class Definition (Python) Source: https://github.com/pallets/itsdangerous/blob/main/docs/serializer.md Defines the Serializer class, its constructor parameters, and their types. This class is used for creating serializer instances with custom configurations for secret keys, salts, serializers, and signers. ```python class itsdangerous.serializer.Serializer( secret_key: str | bytes | Iterable[str] | Iterable[bytes], salt: str | bytes | None = b'itsdangerous', serializer: _PDataSerializer[bytes], serializer_kwargs: dict[str, Any] | None = None, signer: type[Signer] | None = None, signer_kwargs: dict[str, Any] | None = None, fallback_signers: list[dict[str, Any] | tuple[type[Signer], dict[str, Any]]] | type[Signer] | None = None ) ``` -------------------------------- ### Handling Signature Failures by Inspecting Payload (Python) Source: https://github.com/pallets/itsdangerous/blob/main/docs/serializer.md This demonstrates safe inspection of payloads when signature verification fails using try-except blocks. It requires itsdangerous.exc for exception handling and URLSafeSerializer subclass. Purpose is debugging tampered data; limitations include explicit unsafe decoding only when needed to avoid security risks. ```python from itsdangerous.serializer import Serializer from itsdangerous.exc import BadSignature, BadData s = URLSafeSerializer("secret-key") decoded_payload = None try: decoded_payload = s.loads(data) # This payload is decoded and safe except BadSignature as e: if e.payload is not None: try: decoded_payload = s.load_payload(e.payload) except BadData: pass # This payload is decoded but unsafe because someone # tampered with the signature. The decode (load_payload) # step is explicit because it might be unsafe to unserialize # the payload (think pickle instead of json!) ``` -------------------------------- ### itsdangerous.encoding.base64_decode Source: https://github.com/pallets/itsdangerous/blob/main/docs/encoding.md Base64 decodes a URL-safe string of bytes or text. ```APIDOC ## itsdangerous.encoding.base64_decode ### Description Base64 decodes a URL-safe string of bytes or text. The result is bytes. ### Method N/A (Function) ### Endpoint N/A (Function) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```python itsdangerous.encoding.base64_decode(b'aGVsbG8=') ``` ### Response #### Success Response (200) - **return value** (bytes) - The decoded bytes. #### Response Example ```python b'hello' ``` ``` -------------------------------- ### itsdangerous.encoding.base64_encode Source: https://github.com/pallets/itsdangerous/blob/main/docs/encoding.md Base64 encodes a string of bytes or text, producing URL-safe output. ```APIDOC ## itsdangerous.encoding.base64_encode ### Description Base64 encodes a string of bytes or text. The resulting bytes are safe to use in URLs. ### Method N/A (Function) ### Endpoint N/A (Function) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```python itsdangerous.encoding.base64_encode(b'hello') ``` ### Response #### Success Response (200) - **return value** (bytes) - The base64 encoded bytes. #### Response Example ```python b'aGVsbG8=' ``` ``` -------------------------------- ### Apply URL-Safe Timed Serialization in Python Source: https://context7.com/pallets/itsdangerous/llms.txt Combines URL safety, compression, and expiration with URLSafeTimedSerializer. Depends on ItsDangerous; ideal for verification links and API tokens. Handles email verification or authentication with time limits, but ensure secure secret keys. ```python from itsdangerous import URLSafeTimedSerializer, SignatureExpired # Create URL-safe timed serializer s = URLSafeTimedSerializer('secret-key') # Perfect for email verification links def generate_verification_token(email): s = URLSafeTimedSerializer('secret-key', salt='email-verify') return s.dumps({'email': email}) def verify_email_token(token): s = URLSafeTimedSerializer('secret-key', salt='email-verify') try: # Valid for 24 hours data = s.loads(token, max_age=86400) return data['email'] except SignatureExpired: return None # Generate token token = generate_verification_token('user@example.com') verification_url = f'https://example.com/verify?token={token}' print(verification_url) # Verify token email = verify_email_token(token) if email: print(f'Verified email: {email}') else: print('Token expired or invalid') # API authentication tokens api_token = s.dumps({ 'api_key': 'abc123', 'user_id': 42, 'scope': ['read', 'write'] }) # Verify API token (valid for 1 hour) try: auth_data = s.loads(api_token, max_age=3600) print(f"Authenticated user: {auth_data['user_id']}") except SignatureExpired: print('API token expired') ``` -------------------------------- ### Unsafe Loading for Signature Validation (Python) Source: https://github.com/pallets/itsdangerous/blob/main/docs/serializer.md The loads_unsafe method checks signatures without full deserialization, returning a boolean and payload tuple. It depends on the instantiated Serializer and is useful for quick validation. Inputs are signed data; outputs indicate signature validity without raising exceptions. ```python sig_okay, payload = s.loads_unsafe(data) ``` -------------------------------- ### Utilize Timed JSON Serialization in Python Source: https://context7.com/pallets/itsdangerous/llms.txt Combines JSON serialization with expiring signatures using TimedSerializer. Requires ItsDangerous and time; serializes objects with timestamps, deserializes with age checks. Ideal for secure tokens like password resets, but watch for clock synchronization issues. ```python from itsdangerous import TimedSerializer, SignatureExpired import time # Create timed serializer s = TimedSerializer('secret-key') # Serialize with timestamp token = s.dumps({'user_id': 42, 'action': 'password-reset'}) print(token) # '{"user_id":42,"action":"password-reset"}.XyZ...' # Deserialize with age validation try: # Token valid for 5 minutes (300 seconds) data = s.loads(token, max_age=300) print(data) # {'user_id': 42, 'action': 'password-reset'} except SignatureExpired as e: print(f'Token expired at {e.date_signed}') print(f'Data was: {e.payload}') # Get timestamp when loading data, timestamp = s.loads(token, return_timestamp=True, max_age=300) print(f'Token created at: {timestamp}') # Use case: password reset tokens def generate_reset_token(user_id): s = TimedSerializer('secret-key', salt='password-reset') return s.dumps({'user_id': user_id}) def verify_reset_token(token, max_age=3600): s = TimedSerializer('secret-key', salt='password-reset') try: data = s.loads(token, max_age=max_age) return data['user_id'] except SignatureExpired: return None ``` -------------------------------- ### Key Rotation Using List of Secret Keys in Serializer Source: https://github.com/pallets/itsdangerous/blob/main/docs/concepts.md Manages multiple secret keys for signing and validation, enabling periodic rotation to enhance security. Purpose: invalidate compromised keys without disrupting active tokens. Dependencies: itsdangerous.serializer module. Inputs: ordered list of keys (oldest to newest), data. Outputs: signed data validatable against any key. Limitations: Oldest keys are deprecated over time; unrefreshed tokens expire. ```python from itsdangerous.serializer import Serializer SECRET_KEYS = ["2b9cd98e", "169d7886", "b6af09f5"] # sign some data with the latest key s = Serializer(SECRET_KEYS) t = s.dumps({"id": 42}) # rotate a new key in and the oldest key out SECRET_KEYS.append("cf9b3588") del SECRET_KEYS[0] s = Serializer(SECRET_KEYS) s.loads(t) # valid even though it was signed with a previous key ``` -------------------------------- ### Unsign and validate timestamped value in Python Source: https://github.com/pallets/itsdangerous/blob/main/docs/timed.md Shows how to unsign a timestamped value and check if it's expired using max_age. Raises SignatureExpired if the signature is too old. ```python s.unsign(string, max_age=5) Traceback (most recent call last): ... itsdangerous.exc.SignatureExpired: Signature age 15 > 5 seconds ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.