-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathjwt.py
More file actions
169 lines (149 loc) · 6.56 KB
/
jwt.py
File metadata and controls
169 lines (149 loc) · 6.56 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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
import re
import json
from jose import jwt
from six.moves.urllib.request import urlopen
BASE_JWSK_URL = 'https://{tenant_url}/.well-known/jwks.json'
PATTERN = re.compile(r'^Bearer (.*)$')
class RSAKeyNotFoundError(Exception):
pass
class AuthError(Exception):
def __init__(self, error):
self.error = error
class TokenError(Exception):
def __init__(self, error):
self.error = error
class JWKSClient:
_jwks = None
def __init__(
self,
tenant_url: str,
):
self.tenant_url = tenant_url
self.jwks_url = BASE_JWSK_URL.format(
tenant_url=tenant_url
)
self._jwks = self.get_jwks()
def get_jwks(self, force: bool = False):
try:
if not self._jwks or force:
jsonurl = urlopen(self.jwks_url)
self._jwks = json.loads(jsonurl.read())
return self._jwks
except Exception as e:
raise e
class JWT:
_rsa_key = None
verified = False
decoded = None
def __init__(
self,
audience: str,
issuer: str,
token: str,
jwks_client: object
):
self.audience = audience
self.issuer = issuer
self.token = token
self.jwks_client = jwks_client
self.decoded = self._verify()
self._rsa_key = self.get_rsa_key()
def get_rsa_key(self, attempt: bool = True):
def _get_key_from_jwks(jwks: dict, header: dict):
target_rsa_key = list(map(lambda key: {
"kty": key["kty"],
"kid": key["kid"],
"use": key["use"],
"n": key["n"],
"e": key["e"]
}, filter(lambda key: key['kid'] == header['kid'], jwks['keys'])))
return target_rsa_key[0] if target_rsa_key else None
try:
unverified_header = jwt.get_unverified_header(self.token)
if not self._rsa_key:
target_rsa_key = _get_key_from_jwks(self.jwks_client.get_jwks(), unverified_header)
if not target_rsa_key and attempt:
self.jwks_client.get_jwks(force=True)
target_rsa_key = self.get_rsa_key(attempt=False)
if not target_rsa_key:
raise RSAKeyNotFoundError('RSA Key not found in the jwks keys')
self._rsa_key = target_rsa_key
return self._rsa_key
except Exception as e:
raise e
def _verify(self):
target_rsa_key = self.get_rsa_key()
if target_rsa_key:
try:
payload = jwt.decode(
self.token,
target_rsa_key,
algorithms=["RS256"],
audience=self.audience,
issuer=self.issuer
)
return payload
except jwt.ExpiredSignatureError:
raise AuthError({"code": "token_expired",
"description": "token is expired"})
except jwt.JWTClaimsError:
raise AuthError({"code": "invalid_claims",
"description":
"incorrect claims,"
"please check the audience and issuer"})
except Exception:
raise AuthError({"code": "invalid_header",
"description":
"Unable to parse authentication"
" token."})
else:
raise RSAKeyNotFoundError('RSA Key not found in the jwks keys')
@staticmethod
def get_token_authorizer(param: dict):
if not param['type'] or param['type'] != 'TOKEN':
raise TokenError('Expected "event.type" parameter to have value "TOKEN"')
elif not param['authorizationToken']:
raise TokenError('Expected "event.authorizationToken" parameter to be set')
match = PATTERN.match(param['authorizationToken'])
if not match:
raise TokenError('Invalid Authorization token - {token_string} does not match "Bearer .*"'.format(token_string = param['authorizationToken']))
return match[1]
@staticmethod
def get_token_request(param: dict):
if not param['requestContext'] or 'authorizer' not in param['requestContext'] or 'Authorizer' not in param['requestContext']:
raise TokenError('Expected "header.authorization/header.Authorization" parameter to be set')
target_auth_key = 'authorization' if 'authorization' not in param['headers'] else 'Authorization'
match = PATTERN.match(param['headers'][target_auth_key])
if not match:
raise TokenError('Invalid Authorization token - {token_string} does not match "Bearer .*"'.format(token_string = param['authorizationToken']))
return match[1]
@classmethod
def check_scope_from_token(cls, token: str, required_scope: str) -> bool:
unverified_claims = jwt.get_unverified_claims(token)
return cls.check_scope(unverified_claims.get('scope'), required_scope)
@staticmethod
def check_scope(current_scopes: list, required_scope: str) -> bool:
if current_scopes:
token_scopes = current_scopes.split()
for token_scope in token_scopes:
if token_scope == required_scope:
return True
return False
def check_scope_lambda(required_scope: str):
def decorator(func):
def inner(event, context):
try:
if 'requestContext' not in event or 'authorizer' not in event['requestContext'] or ('lambda' not in event['requestContext']['authorizer'] and 'scope' not in event['requestContext']['authorizer']) or ('lambda' in event['requestContext']['authorizer'] and 'scope' not in event['requestContext']['authorizer']['lambda']):
raise TokenError('Expected "requestContext.scope" parameter to be set')
is_valid = JWT.check_scope(event['requestContext']['authorizer']['scope'] if 'scope' in event['requestContext']['authorizer'] else event['requestContext']['authorizer']['lambda']['scope'], required_scope)
if not is_valid:
raise TokenError('Insufficient Scope: Require {scope}'.format(scope=required_scope))
return func(event, context)
except TokenError as e:
print(e)
return {
'statusCode': 403,
'body': json.dumps('unauthorized')
}
return inner
return decorator