Encodes a claims set and returns a JWT string. JWTs are JWS signed objects with a few reserved claims. Args: claims (dict): A claims set to sign key (str or dict): The key to use for signing the claim set. Can be individual JWK or JWK set. algorithm (str
(claims, key, algorithm=ALGORITHMS.HS256, headers=None, access_token=None)
| 22 | |
| 23 | |
| 24 | def encode(claims, key, algorithm=ALGORITHMS.HS256, headers=None, access_token=None): |
| 25 | """Encodes a claims set and returns a JWT string. |
| 26 | |
| 27 | JWTs are JWS signed objects with a few reserved claims. |
| 28 | |
| 29 | Args: |
| 30 | claims (dict): A claims set to sign |
| 31 | key (str or dict): The key to use for signing the claim set. Can be |
| 32 | individual JWK or JWK set. |
| 33 | algorithm (str, optional): The algorithm to use for signing the |
| 34 | the claims. Defaults to HS256. |
| 35 | headers (dict, optional): A set of headers that will be added to |
| 36 | the default headers. Any headers that are added as additional |
| 37 | headers will override the default headers. |
| 38 | access_token (str, optional): If present, the 'at_hash' claim will |
| 39 | be calculated and added to the claims present in the 'claims' |
| 40 | parameter. |
| 41 | |
| 42 | Returns: |
| 43 | str: The string representation of the header, claims, and signature. |
| 44 | |
| 45 | Raises: |
| 46 | JWTError: If there is an error encoding the claims. |
| 47 | |
| 48 | Examples: |
| 49 | |
| 50 | >>> jwt.encode({'a': 'b'}, 'secret', algorithm='HS256') |
| 51 | 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJhIjoiYiJ9.jiMyrsmD8AoHWeQgmxZ5yq8z0lXS67_QGs52AzC8Ru8' |
| 52 | |
| 53 | """ |
| 54 | |
| 55 | for time_claim in ["exp", "iat", "nbf"]: |
| 56 | # Convert datetime to a intDate value in known time-format claims |
| 57 | if isinstance(claims.get(time_claim), datetime): |
| 58 | claims[time_claim] = timegm(claims[time_claim].utctimetuple()) |
| 59 | |
| 60 | if access_token: |
| 61 | claims["at_hash"] = calculate_at_hash(access_token, ALGORITHMS.HASHES[algorithm]) |
| 62 | |
| 63 | return jws.sign(claims, key, headers=headers, algorithm=algorithm) |
| 64 | |
| 65 | |
| 66 | def decode(token, key, algorithms=None, options=None, audience=None, issuer=None, subject=None, access_token=None): |
nothing calls this directly
no test coverage detected
searching dependent graphs…