Parse an ``Authorization`` header value and return an instance, or ``None`` if the value is empty. :param value: The header value to parse. .. versionadded:: 2.3
(cls, value: str | None)
| 88 | |
| 89 | @classmethod |
| 90 | def from_header(cls, value: str | None) -> te.Self | None: |
| 91 | """Parse an ``Authorization`` header value and return an instance, or ``None`` |
| 92 | if the value is empty. |
| 93 | |
| 94 | :param value: The header value to parse. |
| 95 | |
| 96 | .. versionadded:: 2.3 |
| 97 | """ |
| 98 | if not value: |
| 99 | return None |
| 100 | |
| 101 | scheme, _, rest = value.partition(" ") |
| 102 | scheme = scheme.lower() |
| 103 | rest = rest.strip() |
| 104 | |
| 105 | if scheme == "basic": |
| 106 | try: |
| 107 | username, _, password = base64.b64decode(rest).decode().partition(":") |
| 108 | except (binascii.Error, UnicodeError): |
| 109 | return None |
| 110 | |
| 111 | return cls(scheme, {"username": username, "password": password}) |
| 112 | |
| 113 | if "=" in rest.rstrip("="): |
| 114 | # = that is not trailing, this is parameters. |
| 115 | return cls(scheme, parse_dict_header(rest), None) |
| 116 | |
| 117 | # No = or only trailing =, this is a token. |
| 118 | return cls(scheme, None, rest) |
| 119 | |
| 120 | def to_header(self) -> str: |
| 121 | """Produce an ``Authorization`` header value representing this data. |