-
Notifications
You must be signed in to change notification settings - Fork 1.3k
Expand file tree
/
Copy pathtoken_extractor.py
More file actions
51 lines (38 loc) · 1.39 KB
/
token_extractor.py
File metadata and controls
51 lines (38 loc) · 1.39 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
import re
from abc import ABC
from starlette.authentication import (
AuthenticationError,
)
class TokenExtractor(ABC):
"""
A class to extract the authorization token from a user request.
"""
def extract_access_token(self, **kwargs) -> str:
"""
Extract the authorization token from a user request.
The actual implementation has to specify what arguments have to be defined in the kwywork args `kwargs`
Returns:
The extracted access token.
"""
raise NotImplementedError()
def _extract_bearer_token(self, auth_header: str) -> str:
"""
Extract the bearer token from the authorization header value.
Args:
auth_header: The full value of the authorization header.
Returns:
str: The token value, without the `Bearer` part.
Raises:
AuthenticationError if the authorization token does not match the `Bearer` scheme.
"""
pattern = r"(?i)Bearer .+"
if not bool(re.match(pattern, auth_header)):
raise AuthenticationError(f"Expected Bearer schema, found {auth_header}")
_, access_token = auth_header.split()
return access_token
class NoAuthTokenExtractor(TokenExtractor):
"""
A `TokenExtractor` always returning an empty token
"""
def extract_access_token(self, **kwargs) -> str:
return ""