1,103 bytes · the Python implementation · view raw
from typing import Optional
def _is_token_char(ch: str) -> bool:
return ("A" <= ch <= "Z") or ("a" <= ch <= "z") or ("0" <= ch <= "9") or ch in"-._~+/"def parse_bearer_token(authorization: Optional[str]) -> Optional[str]:
"""The token from ``Authorization: Bearer <token>`` (RFC 6750 section 2.1), or None. Never raises: a malformed header is an answer (401), not an error."""ifnot isinstance(authorization, str):
returnNone
value = authorization.strip(" \t")
# Compare the scheme by ASCII case only; str.lower() would also fold# characters the other languages leave alone.
scheme = value[:6]
if len(value) < 7or"".join(chr(ord(c) + 32) if"A" <= c <= "Z"else c for c in scheme) != "bearer"or value[6] != " ":
returnNone
i = 6while i < len(value) and value[i] == " ":
i += 1
token = value[i:]
j = 0while j < len(token) and _is_token_char(token[j]):
j += 1if j == 0:
returnNonewhile j < len(token) and token[j] == "=":
j += 1return token if j == len(token) elseNone