Skip to content

Commit f3a3d43

Browse files
CopilotbgavrilMS
andcommitted
Replace random.sample() with secrets.choice() for PKCE, nonce, and state generation
Co-authored-by: bgavrilMS <12273384+bgavrilMS@users.noreply.github.com>
1 parent 9e6ef48 commit f3a3d43

2 files changed

Lines changed: 5 additions & 5 deletions

File tree

msal/oauth2cli/oauth2.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@
1313
import base64
1414
import sys
1515
import functools
16-
import random
16+
import secrets
1717
import string
1818
import hashlib
1919

@@ -275,7 +275,7 @@ def _scope_set(scope):
275275
def _generate_pkce_code_verifier(length=43):
276276
assert 43 <= length <= 128
277277
verifier = "".join( # https://tools.ietf.org/html/rfc7636#section-4.1
278-
random.sample(string.ascii_letters + string.digits + "-._~", length))
278+
secrets.choice(string.ascii_letters + string.digits + "-._~") for _ in range(length))
279279
code_challenge = (
280280
# https://tools.ietf.org/html/rfc7636#section-4.2
281281
base64.urlsafe_b64encode(hashlib.sha256(verifier.encode("ascii")).digest())
@@ -473,7 +473,7 @@ def initiate_auth_code_flow(
473473
raise ValueError('response_type="token ..." is not allowed')
474474
pkce = _generate_pkce_code_verifier()
475475
flow = { # These data are required by obtain_token_by_auth_code_flow()
476-
"state": state or "".join(random.sample(string.ascii_letters, 16)),
476+
"state": state or "".join(secrets.choice(string.ascii_letters) for _ in range(16)),
477477
"redirect_uri": redirect_uri,
478478
"scope": scope,
479479
}

msal/oauth2cli/oidc.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
import json
22
import base64
33
import time
4-
import random
4+
import secrets
55
import string
66
import warnings
77
import hashlib
@@ -238,7 +238,7 @@ def initiate_auth_code_flow(
238238
# Here we just automatically add it. If the caller do not want id_token,
239239
# they should simply go with oauth2.Client.
240240
_scope.append("openid")
241-
nonce = "".join(random.sample(string.ascii_letters, 16))
241+
nonce = "".join(secrets.choice(string.ascii_letters) for _ in range(16))
242242
flow = super(Client, self).initiate_auth_code_flow(
243243
scope=_scope, nonce=_nonce_hash(nonce), **kwargs)
244244
flow["nonce"] = nonce

0 commit comments

Comments
 (0)