From 005f25afd1c4f7967401b25097928bbca300902a Mon Sep 17 00:00:00 2001 From: Mauro Amico Date: Fri, 14 Jun 2024 09:02:33 +0200 Subject: [PATCH] fix code_verifier_length --- static/pkce.py | 13 +++++++------ 1 file changed, 7 insertions(+), 6 deletions(-) diff --git a/static/pkce.py b/static/pkce.py index 794fa544..935b272a 100644 --- a/static/pkce.py +++ b/static/pkce.py @@ -1,13 +1,14 @@ import hashlib import base64 -import re -import os -import random +import secrets +import string + +# https://datatracker.ietf.org/doc/html/rfc7636#section-4.1 def get_pkce(code_challenge_method: str = "S256", code_challenge_length: int = 64): hashers = {"S256": hashlib.sha256} - code_verifier_length = random.randint(43, 128) - code_verifier = base64.urlsafe_b64encode(os.urandom(code_verifier_length)).decode("utf-8") - code_verifier = re.sub("[^a-zA-Z0-9]+", "", code_verifier) + alpha = string.ascii_letters + string.digits + "-._~" + code_verifier_length = secrets.choice(range(43, 128 + 1)) + code_verifier = "".join([secrets.choice(alpha) for _ in range(code_verifier_length)]) code_challenge = hashers.get(code_challenge_method)( code_verifier.encode("utf-8")