fief_client.pkce
1import base64 2import hashlib 3import secrets 4from typing import Literal 5 6 7def get_code_verifier() -> str: 8 """ 9 Generate a code verifier suitable for PKCE. 10 """ 11 return secrets.token_urlsafe(96) 12 13 14Method = Literal["plain", "S256"] 15 16 17def get_code_challenge(code: str, method: Method = "S256") -> str: 18 """ 19 Generate the PKCE code challenge for the given code and method. 20 21 :param code: The code to generate the challenge for. 22 :param method: The method to use for generating the challenge. Either `plain` or `S256`. 23 """ 24 if method == "plain": 25 return code 26 27 if method == "S256": 28 hasher = hashlib.sha256() 29 hasher.update(code.encode("ascii")) 30 digest = hasher.digest() 31 b64_digest = base64.urlsafe_b64encode(digest).decode("ascii") 32 return b64_digest[:-1] # Remove the padding "=" at the end
def
get_code_verifier() -> str:
8def get_code_verifier() -> str: 9 """ 10 Generate a code verifier suitable for PKCE. 11 """ 12 return secrets.token_urlsafe(96)
Generate a code verifier suitable for PKCE.
Method =
typing.Literal['plain', 'S256']
def
get_code_challenge(code: str, method: Literal['plain', 'S256'] = 'S256') -> str:
18def get_code_challenge(code: str, method: Method = "S256") -> str: 19 """ 20 Generate the PKCE code challenge for the given code and method. 21 22 :param code: The code to generate the challenge for. 23 :param method: The method to use for generating the challenge. Either `plain` or `S256`. 24 """ 25 if method == "plain": 26 return code 27 28 if method == "S256": 29 hasher = hashlib.sha256() 30 hasher.update(code.encode("ascii")) 31 digest = hasher.digest() 32 b64_digest = base64.urlsafe_b64encode(digest).decode("ascii") 33 return b64_digest[:-1] # Remove the padding "=" at the end
Generate the PKCE code challenge for the given code and method.
Parameters
- code: The code to generate the challenge for.
- method: The method to use for generating the challenge. Either
plain
orS256
.