-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathauth.py
251 lines (209 loc) · 6.68 KB
/
auth.py
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
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
"""Logic for authenticating users and verifying permissions for a request.
Attributes:
AUTH0_CLIENT_ID: A str representing the client ID for the Auth0 app
AUTH0_DOMAIN: A str representing the domain for the Auth0 app
ALGORITHMS: A list representing the accepted encryption algorithms for the
access token
API_IDENTIFIER: A str representing the unique identifier for the Auth0 api
Classes:
AuthError()
"""
import json
import os
from functools import wraps
from flask import request
from jose import jwt
from six.moves.urllib.request import urlopen
AUTH0_CLIENT_ID = os.environ["AUTH0_CLIENT_ID"]
AUTH0_DOMAIN = os.environ["AUTH0_DOMAIN"]
ALGORITHMS = ["RS256"]
API_IDENTIFIER = os.environ["API_IDENTIFIER"]
class AuthError(Exception):
"""Creates an exception to handle authorization errors.
Attributes:
error: A dict containing information about the error
status_code: An int representing the http status code
"""
def __init__(self, error, status_code):
"""Set-up for AuthError Exception."""
super().__init__()
self.error = error
self.status_code = status_code
def get_token_auth_header():
"""Obtains the access token from the Authorization Header.
Returns:
token: A str representing the auth token from the Authorization Header
"""
auth = request.headers.get("Authorization", None)
if not auth:
raise AuthError(
{
"error_code": "authorization_header_missing",
"description": "Authorization header is expected",
},
401,
)
parts = auth.split()
if parts[0].lower() != "bearer":
raise AuthError(
{
"error_code": "invalid_header",
"description": "Authorization header must start with Bearer",
},
401,
)
if len(parts) == 1:
raise AuthError(
{
"error_code": "invalid_header",
"description": "Token not found",
},
401,
)
if len(parts) > 2:
raise AuthError(
{
"error_code": "invalid_header",
"description": "Authorization header must be Bearer token",
},
401,
)
token = parts[1]
return token
def get_token_rsa_key(token):
"""Retrieves the rsa key of the provided access token.
Args:
token: A str representing the access token to retrieve the rsa key for
Returns:
rsa_key: A dict representing the rsa key for the the given token
"""
jsonurl = urlopen(f"https://{AUTH0_DOMAIN}/.well-known/jwks.json")
jwks = json.loads(jsonurl.read())
try:
unverified_header = jwt.get_unverified_header(token)
except jwt.JWTError:
raise AuthError(
{
"error_code": "invalid_header",
"description": (
"Invalid header. Use an RS256 signed JWT Access Token"
),
},
401,
)
if unverified_header["alg"] == "HS256":
raise AuthError(
{
"error_code": "invalid_header",
"description": (
"Invalid header. Use an RS256 signed JWT Access Token"
),
},
401,
)
rsa_key = {}
for key in jwks["keys"]:
if key["kid"] == unverified_header["kid"]:
rsa_key = {
"kty": key["kty"],
"kid": key["kid"],
"use": key["use"],
"n": key["n"],
"e": key["e"],
}
if not rsa_key:
raise AuthError(
{
"error_code": "invalid_header",
"description": "Unable to find appropriate key",
},
401,
)
return rsa_key
def verify_decode_jwt(token, rsa_key):
"""Decodes and verifies the validity of the provided access token.
Args:
token: A str representing the access token to be decoded and verified
rsa_key: A dict representing the rsa key for the the given token
Returns:
payload: A dict representing the decoded and verified access token
"""
try:
payload = jwt.decode(
token,
rsa_key,
algorithms=ALGORITHMS,
audience=API_IDENTIFIER,
issuer=f"https://{AUTH0_DOMAIN}/",
)
except jwt.ExpiredSignatureError:
raise AuthError(
{
"error_code": "token_expired",
"description": "Token is expired",
},
401,
)
except jwt.JWTClaimsError:
raise AuthError(
{
"error_code": "invalid_claims",
"description": (
"Incorrect claims, please check the audience and " "issuer"
),
},
401,
)
except Exception:
raise AuthError(
{
"error_code": "invalid_header",
"description": "Unable to parse authentication token",
},
401,
)
return payload
def check_permissions(permission, payload):
"""Checks if a decoded access token contains the required peermission.
Args:
permission: A str representing the required permission
payload: A dict representing the decoded access token
"""
permissions = payload.get("permissions")
if permissions is None:
raise AuthError(
{
"error_code": "invalid_claims",
"description": (
"Incorrect claims, please check the role-based access "
"control settings"
),
},
401,
)
if permission not in permissions:
raise AuthError(
{
"error_code": "forbidden",
"description": (
"You are not authorized to access this resource"
),
},
403,
)
def requires_auth(permission=""):
"""A decorator to authenticate users and verify permissions for a request.
Args:
permission: A str representing the permission required to access the
requested resource
"""
def requires_auth_decorator(f):
@wraps(f)
def wrapper(*args, **kwargs):
token = get_token_auth_header()
rsa_key = get_token_rsa_key(token)
payload = verify_decode_jwt(token, rsa_key)
check_permissions(permission, payload)
return f(*args, **kwargs)
return wrapper
return requires_auth_decorator