-
-
Notifications
You must be signed in to change notification settings - Fork 207
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
3e0934f
commit 1314595
Showing
3 changed files
with
35 additions
and
17 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,27 +1,41 @@ | ||
import re | ||
from typing import Dict | ||
|
||
BASE64URL_REGEX = r"^([a-z0-9_-]{4})*($|[a-z0-9_-]{3}$|[a-z0-9_-]{2}$)$" | ||
|
||
|
||
def is_jwt(value: str) -> bool: | ||
if value.startswith("Bearer "): | ||
value = value.replace("Bearer ", "") | ||
def is_valid_jwt(value: str) -> bool: | ||
"""Checks if value looks like a JWT, does not do any extra parsing.""" | ||
if not isinstance(value, str): | ||
return False | ||
|
||
# Remove trailing whitespaces if any. | ||
value = value.strip() | ||
if not value: | ||
return False | ||
|
||
parts = value.split(".") | ||
if len(parts) != 3: | ||
# Remove "Bearer " prefix if any. | ||
if value.startswith("Bearer "): | ||
value = value[7:] | ||
|
||
# Valid JWT must have 2 dots (Header.Paylod.Signature) | ||
if value.count(".") != 2: | ||
return False | ||
|
||
# loop through the parts and test against regex | ||
for part in parts: | ||
if len(part) < 4 or not re.search(BASE64URL_REGEX, part, re.IGNORECASE): | ||
for part in value.split("."): | ||
if not re.search(BASE64URL_REGEX, part, re.IGNORECASE): | ||
return False | ||
|
||
return True | ||
|
||
|
||
def check_authorization_header(headers): | ||
def check_authorization_header(headers: Dict[str, str]): | ||
authorization = headers.get("Authorization") | ||
if not authorization: | ||
return | ||
|
||
if authorization.startswith("Bearer "): | ||
if not is_valid_jwt(authorization): | ||
raise ValueError( | ||
"create_client called with global Authorization header that does not contain a JWT" | ||
) | ||
|
||
return True |