### Sign and Verify JWS Tokens with python-jose Source: https://context7.com/mpdavis/python-jose/llms.txt Provides examples for creating JSON Web Signatures (JWS) with arbitrary payloads and custom headers, and for verifying these signatures. It covers both direct payload signing and extracting unverified headers. The output of signing is a compact serialization of the JWS. ```python from jose import jws import json # Sign arbitrary payload payload = {'transaction_id': 'tx-12345', 'amount': 100.50} token = jws.sign(payload, 'secret', algorithm='HS256') # Returns: 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ0cmFuc2FjdGlvbl9pZCI6InR4LTEyMzQ1IiwiYW1vdW50IjoxMDAuNX0.xyz...' # Verify and extract payload (returns bytes) verified_payload_bytes = jws.verify(token, 'secret', algorithms=['HS256']) verified_payload = json.loads(verified_payload_bytes) print(verified_payload) # Returns: {'transaction_id': 'tx-12345', 'amount': 100.5} # Sign with custom headers headers = {'kid': 'signing-key-2024', 'custom': 'value'} token = jws.sign(payload, 'secret', headers=headers, algorithm='HS256') # Get unverified header header = jws.get_unverified_header(token) print(header) # Returns: {'alg': 'HS256', 'typ': 'JWT', 'kid': 'signing-key-2024', 'custom': 'value'} ``` -------------------------------- ### Encode and Decode JWT with Python-JOSE Source: https://github.com/mpdavis/python-jose/blob/master/README.rst Demonstrates how to encode and decode JSON Web Tokens (JWT) using the python-jose library. This example shows creating a token with a secret key and then decoding it to verify its contents. It utilizes the 'HS256' algorithm. ```python >>> from jose import jwt >>> token = jwt.encode({'key': 'value'}, 'secret', algorithm='HS256') u'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJrZXkiOiJ2YWx1ZSJ9.FG-8UppwHaFp1LgRYQQeS6EDQF7_6-bMFegNucHjmWg' >>> jwt.decode(token, 'secret', algorithms=['HS256']) {u'key': u'value'} ``` -------------------------------- ### Extract public key from X.509 certificate using OpenSSL (Bash) Source: https://github.com/mpdavis/python-jose/blob/master/docs/jwk/index.md Shows how to convert an X.509 certificate to a PEM-formatted public key that can be used with python-jose. The OpenSSL command reads the certificate file and outputs the public key. Requires OpenSSL installed and a valid certificate file (cert.pem). ```bash openssl x509 -pubkey -noout < cert.pem ``` -------------------------------- ### Verify JWS Token Signature with Python JOSE Source: https://github.com/mpdavis/python-jose/blob/master/docs/jws/index.md Example of verifying the signature of a JWS token using the python-jose library. This function takes a signed token, the secret key, and a list of allowed algorithms to return the original payload if the signature is valid. It requires the 'jose' library. ```python jws.verify(signed, 'secret', algorithms=['HS256']) ``` -------------------------------- ### Sign JWS Token with Python JOSE Source: https://github.com/mpdavis/python-jose/blob/master/docs/jws/index.md Example of signing a JSON object into a JWS token using the python-jose library. This function takes a payload, a secret key, and a specified algorithm to generate a signed token. It requires the 'jose' library. ```python from jose import jws signed = jws.sign({'a': 'b'}, 'secret', algorithm='HS256') ``` -------------------------------- ### Get Unverified Claims from JWT (Python) Source: https://github.com/mpdavis/python-jose/blob/master/docs/jwt/api.md This function retrieves the claims from a JWT without performing any signature verification. Useful for scenarios where signature validation is not immediately needed. Raises JWTError if decoding fails. ```Python >>> import jose.jwt >>> jwt.get_unverified_claims('eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJhIjoiYiJ9.jiMyrsmD8AoHWeQgmxZ5yq8z0lXS67_QGs52AzC8Ru8') ``` -------------------------------- ### Get Unverified Claims from JWS Token Source: https://github.com/mpdavis/python-jose/blob/master/docs/jws/api.md Retrieves the decoded claims from a JWS token without performing any signature verification. It takes a JWS string as input and returns the claims as a string. Raises JWSError if decoding fails. ```python import jose.jws token = "your_jws_token_here" claims = jose.jws.get_unverified_claims(token) ``` -------------------------------- ### Customize JWT Validation Options in Python Source: https://context7.com/mpdavis/python-jose/llms.txt Shows how to use flexible validation options for permissive or strict JWT decoding. Applies to python-jose jwt module. Inputs are token, secret, algorithms, and options dict; outputs decoded claims. Allows customization of checks like expiration, audience. Limited to HS256 algorithm in examples. ```python from jose import jwt # Permissive validation (development/testing) options_permissive = { 'verify_signature': True, 'verify_exp': False, # Don't check expiration 'verify_nbf': False, # Don't check not-before 'verify_iat': False, # Don't check issued-at 'verify_aud': False, # Don't check audience 'require_exp': False, # Don't require exp claim 'require_iat': False, # Don't require iat claim 'require_nbf': False # Don't require nbf claim } decoded = jwt.decode(token, 'secret', algorithms=['HS256'], options=options_permissive) # Strict validation (production) options_strict = { 'verify_signature': True, 'verify_exp': True, 'verify_nbf': True, 'verify_iat': True, 'verify_aud': True, 'require_exp': True, 'require_iat': True, 'leeway': 0 # No time leeway } decoded = jwt.decode( token, 'secret', algorithms=['HS256'], audience='myapp', issuer='auth-service', subject='user123', options=options_strict ) ``` -------------------------------- ### Get Unverified Header from JWT (Python) Source: https://github.com/mpdavis/python-jose/blob/master/docs/jwt/api.md This function retrieves the header information from a JWT without signature verification. Useful for inspecting JWT structure without validating its authenticity. Raises JWTError if decoding fails. ```Python >>> import jose.jwt >>> jwt.get_unverified_header('eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJhIjoiYiJ9.jiMyrsmD8AoHWeQgmxZ5yq8z0lXS67_QGs52AzC8Ru8') ``` -------------------------------- ### Get Unverified Headers from JWS Token Source: https://github.com/mpdavis/python-jose/blob/master/docs/jws/api.md Retrieves the decoded headers from a JWS token without performing any signature verification. This function is a wrapper for backwards compatibility. It takes a JWS string as input and returns the headers as a dictionary. Raises JWSError if decoding fails. ```python import jose.jws token = "your_jws_token_here" headers = jose.jws.get_unverified_header(token) ``` -------------------------------- ### Get JWE Header - Python Source: https://github.com/mpdavis/python-jose/blob/master/docs/jwe/api.md Returns the decoded header values from a compact serialized JWE string without performing any verification of the token's integrity or authenticity. Useful for inspecting token metadata before processing. Requires a valid JWE string and returns a dictionary representation of the header fields. Does not validate the token and should be used cautiously for untrusted input. ```python from jose import jwe jwe.get_unverified_header(jwe_str) ``` -------------------------------- ### Sign and Verify JWS with Key Objects in Python Source: https://context7.com/mpdavis/python-jose/llms.txt This snippet shows how to sign a payload using a constructed key for JWS and verify it. It demonstrates symmetric signing with HS256 and constructing an RSA key from PEM. Dependencies include the python-jose library. Inputs are payload and key, outputs the verified payload. Assumes valid key formats and no limitations on key types beyond RSA. ```python # Use constructed key payload = {'user': 'alice', 'action': 'read'} token = jws.sign(payload, key_obj, algorithm='HS256') verified = jws.verify(token, key_obj, algorithms=['HS256']) print(json.loads(verified)) # Returns: {'user': 'alice', 'action': 'read'} # Construct from RSA PEM rsa_key_pem = """-----BEGIN PUBLIC KEY----- MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA... -----END PUBLIC KEY-----""" rsa_key_obj = jwk.construct(rsa_key_pem, algorithm='RS256') ``` -------------------------------- ### RSA Key Pair Authentication for JWT in Python Source: https://context7.com/mpdavis/python-jose/llms.txt Demonstrates signing JWTs using an RSA private key and verifying them with the corresponding public key. This is essential for asymmetric authentication in distributed systems where the public key can be securely shared. ```python from jose import jwt from jose.exceptions import JWTError # RSA private key (PEM format) private_key = """-----BEGIN RSA PRIVATE KEY----- MIIEowIBAAKCAQEA4f5wg5l2hKsTeNem/V41fGnJm6gOdrj8ym3rFkEU/wT8RDtn SgFEZOQpHEgQ7JL38xUfU0Y3g6aYw9QT0hJ7mCpz9Er5qLaMXJwZxzHzAahlfA0i cqabvJOMvQtzD6uQv6wPEyZtDTWiQi9AXwBpHssPnpYGIn20ZZuNlX2BrClciHqj ... -----END RSA PRIVATE KEY-----""" # RSA public key (PEM format) public_key = """-----BEGIN PUBLIC KEY----- MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA4f5wg5l2hKsTeNem/V41 fGnJm6gOdrj8ym3rFkEU/wT8RDtnSgFEZOQpHEgQ7JL38xUfU0Y3g6aYw9QT0hJ7 ... -----END PUBLIC KEY----- """ # Sign with private key token = jwt.encode( {'sub': 'user123', 'action': 'payment'}, private_key, algorithm='RS256' ) # Verify with public key try: decoded = jwt.decode(token, public_key, algorithms=['RS256']) print(f"Valid token for user: {decoded['sub']}") except JWTError as e: print(f"Invalid token: {e}") ``` -------------------------------- ### Verify token signature using python-jose (Python) Source: https://github.com/mpdavis/python-jose/blob/master/docs/jwk/index.md Demonstrates how to verify a JWT's signature with a symmetric HMAC key using the python-jose library. It imports required modules, constructs a JWK from a JSON dict, splits the token, decodes the signature, and validates it. Requires python-jose and its dependencies; works with HS256-signed tokens. ```python >>> from jose import jwk >>> from jose.utils import base64url_decode >>> >>> token = "eyJhbGciOiJIUzI1NiIsImtpZCI6IjAxOGMwYWU1LTRkOWItNDcxYi1iZmQ2LWVlZjMxNGJjNzAzNyJ9.SXTigJlzIGEgZGFuZ2Vyb3VzIGJ1c2luZXNzLCBGcm9kbywgZ29pbmcgb3V0IHlvdXIgZG9vci4gWW91IHN0ZXAgb250byB0aGUgcm9hZCwgYW5kIGlmIHlvdSBkb24ndCBrZWVwIHlvdXIgZmVldCwgdGhlcmXigJlzIG5vIGtub3dpbmcgd2hlcmUgeW91IG1pZ2h0IGJlIHN3ZXB0IG9mZiB0by4.s0h6KThzkfBBBkLspW1h84VsJZFTsPPqMDA7g1Md7p0" >>> hmac_key = { ... "kty": "oct", ... "kid": "018c0ae5-4d9b-471b-bfd6-eef314bc7037", ... "use": "sig", ... "alg": "HS256", ... "k": "hJtXIZ2uSN5kbQfbtTNWbpdmhkV8FJG-Onbc6mxCcYg" ... } >>> >>> key = jwk.construct(hmac_key) >>> >>> message, encoded_sig = token.rsplit('.', 1) >>> decoded_sig = base64url_decode(encoded_sig.encode()) >>> key.verify(message, decoded_sig) ``` -------------------------------- ### Construct JWK Key Objects using python-jose Source: https://context7.com/mpdavis/python-jose/llms.txt Shows how to create cryptographic key objects from various sources, including raw symmetric keys, JWK dictionaries, and potentially PEM-encoded keys (though not explicitly shown in this snippet). These key objects can then be used directly with signing and verification functions. ```python from jose import jwk, jws import json # Construct from raw symmetric key key_obj = jwk.construct('my-secret-key', algorithm='HS256') token = jws.sign({'data': 'value'}, key_obj, algorithm='HS256') # Construct from JWK dictionary jwk_data = { 'kty': 'oct', # Key type: octet sequence (symmetric) 'k': 'GawgguFyGrWKav7AX4VKUg', # Base64url encoded key 'alg': 'HS256' } key_obj = jwk.construct(jwk_data, algorithm='HS256') ``` -------------------------------- ### Encrypt and Decrypt JWE with RSA Key Wrapping using python-jose Source: https://context7.com/mpdavis/python-jose/llms.txt Demonstrates encrypting data using JWE with RSA keys for key wrapping, allowing secure distribution of symmetric content encryption keys. It shows how to encrypt using an RSA public key and decrypt using the corresponding private key. Metadata like the encryption algorithm and mode can be retrieved without decryption. ```python from jose import jwe # RSA public key for encryption rsa_public_key = "-----BEGIN PUBLIC KEY-----\nMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA...\n-----END PUBLIC KEY-----" # RSA private key for decryption rsa_private_key = "-----BEGIN RSA PRIVATE KEY-----\nMIIEowIBAAKCAQEA...\n-----END RSA PRIVATE KEY-----" plaintext = 'Sensitive data to encrypt' # Encrypt with RSA-OAEP key wrapping encrypted = jwe.encrypt( plaintext, rsa_public_key, algorithm='RSA-OAEP', # RSA-OAEP key wrapping encryption='A256GCM' # AES-256 GCM for content ) # Decrypt with RSA private key decrypted = jwe.decrypt(encrypted, rsa_private_key) print(decrypted.decode('utf-8')) # Returns: 'Sensitive data to encrypt' # Get encryption metadata without decrypting header = jwe.get_unverified_header(encrypted) print(header) # Returns: {'alg': 'RSA-OAEP', 'enc': 'A256GCM'} ``` -------------------------------- ### Encrypt Plaintext to JWE - Python Source: https://github.com/mpdavis/python-jose/blob/master/docs/jwe/api.md Encrypts plaintext using specified algorithm and key, producing a JWE compact serialization string. Supports configurable encryption algorithms (default A256GCM), content encryption algorithms, compression, content type, and key ID. Returns a base64-encoded string containing header, encrypted key, IV, ciphertext, and authentication tag. Raises JWEError on encryption failures. ```python from jose import jwe jwe.encrypt('Hello, World!', 'asecret128bitkey', algorithm='dir', encryption='A128GCM') ``` -------------------------------- ### Handle JOSE and JWT Exceptions in Python Source: https://context7.com/mpdavis/python-jose/llms.txt Illustrates exception handling for various JOSE errors during token validation. Uses python-jose exceptions. Inputs are token and secret; outputs validation result dict. Covers specific error types for better user feedback. Does not handle all possible exceptions beyond listed ones. ```python from jose import jwt from jose.exceptions import ( JOSEError, JWTError, JWTClaimsError, ExpiredSignatureError, JWSError, JWSSignatureError, JWEError ) def validate_token(token, secret): try: decoded = jwt.decode(token, secret, algorithms=['HS256']) return {'valid': True, 'claims': decoded} except ExpiredSignatureError: return {'valid': False, 'error': 'Token has expired'} except JWTClaimsError as e: return {'valid': False, 'error': f'Invalid claims: {str(e)}'} except JWSSignatureError: return {'valid': False, 'error': 'Invalid signature'} except JWTError as e: return {'valid': False, 'error': f'JWT error: {str(e)}'} except JOSEError as e: return {'valid': False, 'error': f'JOSE error: {str(e)}'} # Usage result = validate_token(user_token, 'secret') if result['valid']: print(f"Authenticated user: {result['claims']['sub']}") else: print(f"Authentication failed: {result['error']}") ``` -------------------------------- ### Encode JWT Tokens in Python Source: https://context7.com/mpdavis/python-jose/llms.txt Creates signed JSON Web Tokens (JWT) with specified claims and optional custom headers. Requires claims, a signing key, and an algorithm. Supports standard claims and custom headers for additional metadata. ```python from jose import jwt from datetime import datetime, timedelta try: from datetime import UTC except ImportError: from datetime import timezone UTC = timezone.utc # Basic encoding token = jwt.encode({'user_id': '12345', 'role': 'admin'}, 'secret', algorithm='HS256') # Returns: 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyX2lkIjoiMTIzNDUiLCJyb2xlIjoiYWRtaW4ifQ.xyz...' # Encoding with standard claims and custom headers claims = { 'sub': 'user123', 'aud': 'myapp', 'iss': 'auth-service', 'exp': datetime.now(UTC) + timedelta(hours=1), 'iat': datetime.now(UTC), 'nbf': datetime.now(UTC), 'jti': 'token-unique-id', 'custom_claim': 'custom_value' } headers = { 'kid': 'key-2024-01', 'custom-header': 'metadata' } token = jwt.encode(claims, 'secret', algorithm='HS256', headers=headers) ``` -------------------------------- ### Validate OpenID Connect ID Tokens in Python Source: https://context7.com/mpdavis/python-jose/llms.txt Demonstrates encoding and decoding OpenID Connect ID tokens with automatic at_hash verification for security. Uses python-jose's jwt module. Inputs include claims, secret, and access token; outputs decoded claims or error. Requires datetime module and handles exceptions like JWTError. ```python from jose import jwt # Issuer creates ID token with access token hash access_token = 'ya29.a0AfH6SMBx...' # OAuth 2.0 access token id_token = jwt.encode( { 'sub': 'user123', 'aud': 'client-id-123', 'iss': 'https://accounts.example.com', 'exp': datetime.now(UTC) + timedelta(hours=1), 'iat': datetime.now(UTC) }, 'secret', algorithm='HS256', access_token=access_token # Automatically calculates and adds at_hash claim ) # Relying party validates ID token with access token try: decoded = jwt.decode( id_token, 'secret', algorithms=['HS256'], audience='client-id-123', issuer='https://accounts.example.com', access_token=access_token # Validates at_hash matches access_token ) print(f"Valid ID token for subject: {decoded['sub']}") except JWTError as e: print(f"ID token validation failed: {e}") ``` -------------------------------- ### Inspect JWT Headers and Claims Unverified in Python Source: https://context7.com/mpdavis/python-jose/llms.txt Extracts headers and claims from a JSON Web Token (JWT) without performing cryptographic verification. This is useful for determining the necessary key for subsequent validation. Use 'get_unverified_claims' with caution as it bypasses security checks. ```python from jose import jwt # Assume 'token' is a JWT string token = 'eyJhbGciOiJSUzI1NiIsImtpZCI6ImtleS0yMDI0LTAxIn0.eyJzdWIiOiJ1c2VyMTIzIn0.sig...' # Get header without verification header = jwt.get_unverified_header(token) print(header) # Returns: {'alg': 'RS256', 'typ': 'JWT', 'kid': 'key-2024-01'} # Use kid to select the correct key (example function) def get_key_from_store(kid): # Replace with actual key retrieval logic pass kid = header.get('kid') key = get_key_from_store(kid) decoded = jwt.decode(token, key, algorithms=['RS256']) # Example validation after getting key # Get claims without verification (use with caution) claims = jwt.get_unverified_claims(token) print(claims) # Returns: {'sub': 'user123'} ``` -------------------------------- ### Encode JWT with Python Source: https://github.com/mpdavis/python-jose/blob/master/docs/jwt/api.md This function encodes a claims set into a JWT string, allowing specification of the algorithm and optional headers. It uses a provided key to sign the claims and optionally calculates an access token hash. Raises JWTError if encoding fails. ```Python >>> import jose.jwt >>> jwt.encode({'a': 'b'}, 'secret', algorithm='HS256') ``` -------------------------------- ### Encrypt and Decrypt JWE with Symmetric Keys using python-jose Source: https://context7.com/mpdavis/python-jose/llms.txt Illustrates JSON Web Encryption (JWE) for encrypting sensitive data using a direct symmetric key. It supports various encryption algorithms, including AES-256 GCM, and can optionally apply DEFLATE compression for large payloads. The process involves encrypting plaintext and then decrypting the ciphertext back to its original form. ```python from jose import jwe import json # Direct symmetric encryption (algorithm='dir') key = b'a256bitkeya256bitkeya256bitk' # 32 bytes for A256GCM plaintext = json.dumps({'ssn': '123-45-6789', 'credit_card': '4111111111111111'}) encrypted = jwe.encrypt( plaintext, key, algorithm='dir', # Direct use of shared symmetric key encryption='A256GCM' # AES-256 GCM encryption ) # Returns: 'eyJhbGciOiJkaXIiLCJlbmMiOiJBMjU2R0NNIn0..IV..ciphertext..auth_tag' # Decrypt decrypted_bytes = jwe.decrypt(encrypted, key) decrypted = json.loads(decrypted_bytes) print(decrypted) # Returns: {'ssn': '123-45-6789', 'credit_card': '4111111111111111'} # Encryption with compression for large payloads large_data = {'data': 'x' * 10000} encrypted_compressed = jwe.encrypt( json.dumps(large_data), key, algorithm='dir', encryption='A256GCM', zip='DEF' # DEFLATE compression ) decrypted_large = jwe.decrypt(encrypted_compressed, key) ``` -------------------------------- ### Sign Payload to Create JWS Token Source: https://github.com/mpdavis/python-jose/blob/master/docs/jws/api.md Signs a given payload using a specified key and algorithm, returning a JWS string. Optionally accepts custom headers to merge with default ones. The payload can be a string or dictionary, and the key can be a string or JWK dictionary. Defaults to HS256 algorithm. Raises JWSError on signing errors. ```python import jose.jws payload = {'user_id': 123, 'username': 'testuser'} secret_key = 'your-secret-key' jws_token = jose.jws.sign(payload, secret_key, algorithm='HS256') print(jws_token) ``` -------------------------------- ### Verify JWS Token Signature Source: https://github.com/mpdavis/python-jose/blob/master/docs/jws/api.md Verifies the signature of a JWS token using the provided key and a list of allowed algorithms. If verification is successful, it returns the payload as a string. The `verify` parameter defaults to True. Raises JWSError if the signature is invalid or verification fails. ```python import jose.jws token = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJhIjoiYiJ9.jiMyrsmD8AoHWeQgmxZ5yq8z0lXS67_QGs52AzC8Ru8' secret_key = 'your-secret-key' # Assuming the token was signed with HS256 allowed_algorithms = ['HS256'] verified_payload = jose.jws.verify(token, secret_key, algorithms=allowed_algorithms) print(verified_payload) ``` -------------------------------- ### Validate JWT with Multiple Keys and JWK Sets using python-jose Source: https://context7.com/mpdavis/python-jose/llms.txt Demonstrates validating JWTs against a list of shared secrets or a JWK Set. This is useful for scenarios involving key rotation or multi-tenant applications where multiple keys might be valid. It handles token validation by iterating through provided keys or JWK Set entries. ```python from jose import jwt, JWTError # Using a list of keys (tries each until one works) keys = ['old-secret', 'current-secret', 'new-secret'] try: decoded = jwt.decode(token, keys, algorithms=['HS256']) print("Token validated with one of the keys") except JWTError: print("Token invalid with all keys") # Using JWK Set (RFC 7517 format) jwk_set = { 'keys': [ { 'kty': 'oct', 'kid': 'key-1', 'k': 'GawgguFyGrWKav7AX4VKUg', # base64url encoded secret 'alg': 'HS256' }, { 'kty': 'oct', 'kid': 'key-2', 'k': 'AyM1SysPpbyDfgZld3umj1qzKObwVMkoqQ-EstJQLr_T-1qS0gZH75aKtMN3Yj0iPS4hcgUuTwjAzZr1Z9CAow', 'alg': 'HS256' } ] } # Decode with JWK Set decoded = jwt.decode(token, jwk_set, algorithms=['HS256']) # Using individual JWK jwk_key = { 'kty': 'oct', 'k': 'GawgguFyGrWKav7AX4VKUg', 'alg': 'HS256' } decoded = jwt.decode(token, jwk_key, algorithms=['HS256']) ``` -------------------------------- ### Encrypt Payload with JWE in Python Source: https://github.com/mpdavis/python-jose/blob/master/docs/jwe/index.md Encrypts a given payload using specified JWE algorithms. Requires the 'jose' library. It takes the payload, a secret key, the key management algorithm, and the content encryption algorithm as input, returning a JWE compact serialization string. ```python from jose import jwe jwe.encrypt('Hello, World!', 'asecret128bitkey', algorithm='dir', encryption='A128GCM') 'eyJhbGciOiJkaXIiLCJlbmMiOiJBMTI4R0NNIn0..McILMB3dYsNJSuhcDzQshA.OfX9H_mcUpHDeRM4IA.CcnTWqaqxNsjT4eCaUABSg' ``` -------------------------------- ### Decode and Validate JWT Tokens in Python Source: https://context7.com/mpdavis/python-jose/llms.txt Decodes and verifies JSON Web Tokens (JWT), including signature verification and validation of standard claims like expiration, audience, and issuer. Handles potential JWT errors and claim validation failures. ```python from jose import jwt from jose.exceptions import JWTError, ExpiredSignatureError, JWTClaimsError # Assume 'token' is a previously generated JWT string # Basic decoding with signature verification try: decoded = jwt.decode(token, 'secret', algorithms=['HS256']) print(decoded) # Returns: {'user_id': '12345', 'role': 'admin'} except ExpiredSignatureError: print("Token has expired") except JWTClaimsError as e: print(f"Invalid claims: {e}") except JWTError as e: print(f"JWT error: {e}") # Decoding with claim validation decoded = jwt.decode( token, 'secret', algorithms=['HS256'], audience='myapp', issuer='auth-service', options={ 'verify_signature': True, 'verify_exp': True, 'verify_aud': True, 'require_exp': True, 'require_iat': True, 'leeway': 10 # 10 seconds leeway for time validation }) ``` -------------------------------- ### Decrypt JWE Token - Python Source: https://github.com/mpdavis/python-jose/blob/master/docs/jwe/api.md Decrypts a JWE compact serialized string using the provided key and returns the original plaintext. Requires a valid JWE string and appropriate decryption key (individual JWK or JWK set). Returns bytes representing the decrypted content and raises JWEError if authentication fails or token is invalid. ```python from jose import jwe jwe.decrypt(jwe_string, 'asecret128bitkey') ``` -------------------------------- ### Decode JWT with Python Source: https://github.com/mpdavis/python-jose/blob/master/docs/jwt/api.md This function decodes a JWT and validates its signature, with options for specifying algorithms and audience. It handles different key formats (string, tuple, list, JSON string, JWK set). Returns the claims set if successful, raises JWTError otherwise. ```Python >>> payload = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJhIjoiYiJ9.jiMyrsmD8AoHWeQgmxZ5yq8z0lXS67_QGs52AzC8Ru8' >>> import jose.jwt >>> jwt.decode(payload, 'secret', algorithms='HS256') ``` -------------------------------- ### Decrypt Payload with JWE in Python Source: https://github.com/mpdavis/python-jose/blob/master/docs/jwe/index.md Decrypts a JWE compact serialization string using the provided secret key. Requires the 'jose' library. It takes the JWE string and the secret key as input, returning the original decrypted payload. ```python from jose import jwe jwe.decrypt('eyJhbGciOiJkaXIiLCJlbmMiOiJBMTI4R0NNIn0..McILMB3dYsNJSuhcDzQshA.OfX9H_mcUpHDeRM4IA.CcnTWqaqxNsjT4eCaUABSg', 'asecret128bitkey') 'Hello, World!' ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.