Newer
Older
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
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
import datetime
import logging
import time
import warnings
from json import JSONEncoder
import jwt
from pyramid.renderers import JSON
from webob.cookies import CookieProfile
from zope.interface import implementer
from pyramid.authentication import CallbackAuthenticationPolicy
from pyramid.interfaces import IAuthenticationPolicy, IRendererFactory
from pyramid.request import Request
log = logging.getLogger(__name__)
marker = []
# Adapted from https://github.com/wichert/pyramid_jwt
# Cookie creation was rewritten because the previous method would base64 encode the JWT
class PyramidJSONEncoderFactory(JSON):
def __init__(self, pyramid_registry=None, **kw):
super().__init__(**kw)
self.registry = pyramid_registry
def __call__(self, *args, **kwargs):
json_renderer = None
if self.registry is not None:
json_renderer = self.registry.queryUtility(
IRendererFactory, "json", default=JSONEncoder
)
request = kwargs.get("request")
if not kwargs.get("default") and isinstance(json_renderer, JSON):
self.components = json_renderer.components
kwargs["default"] = self._make_default(request)
return JSONEncoder(*args, **kwargs)
json_encoder_factory = PyramidJSONEncoderFactory(None)
@implementer(IAuthenticationPolicy)
class JWTAuthenticationPolicy(CallbackAuthenticationPolicy):
def __init__(
self,
private_key,
public_key=None,
algorithm="HS512",
leeway=0,
expiration=None,
default_claims=None,
http_header="Authorization",
auth_type="JWT",
callback=None,
json_encoder=None,
audience=None,
):
self.private_key = private_key
self.public_key = public_key if public_key is not None else private_key
self.algorithm = algorithm
self.leeway = leeway
self.default_claims = default_claims if default_claims else {}
self.http_header = http_header
self.auth_type = auth_type
if expiration:
if not isinstance(expiration, datetime.timedelta):
expiration = datetime.timedelta(seconds=expiration)
self.expiration = expiration
else:
self.expiration = None
if audience:
self.audience = audience
else:
self.audience = None
self.callback = callback
if json_encoder is None:
json_encoder = json_encoder_factory
self.json_encoder = json_encoder
self.jwt_std_claims = ("sub", "iat", "exp", "aud")
def create_token(self, principal, expiration=None, audience=None, **claims):
payload = self.default_claims.copy()
payload.update(claims)
payload["sub"] = principal
payload["iat"] = iat = datetime.datetime.utcnow()
expiration = expiration or self.expiration
audience = audience or self.audience
if expiration:
if not isinstance(expiration, datetime.timedelta):
expiration = datetime.timedelta(seconds=expiration)
payload["exp"] = iat + expiration
if audience:
payload["aud"] = audience
token = jwt.encode(
payload,
self.private_key,
algorithm=self.algorithm,
json_encoder=self.json_encoder,
)
if not isinstance(token, str): # Python3 unicode madness
token = token.decode("ascii")
return token
def get_claims(self, request: Request):
if self.http_header == "Authorization":
try:
if request.authorization is None:
return {}
except ValueError: # Invalid Authorization header
return {}
(auth_type, token) = request.authorization
if auth_type != self.auth_type:
return {}
else:
token = request.headers.get(self.http_header)
if not token:
return {}
return self.jwt_decode(request, token)
def jwt_decode(self, request: Request, token: str):
try:
claims = jwt.decode(
token,
self.public_key,
algorithms=[self.algorithm],
leeway=self.leeway,
audience=self.audience,
)
return claims
except jwt.InvalidTokenError as e:
log.warning("Invalid JWT token from %s: %s", request.remote_addr, e)
return {}
def unauthenticated_userid(self, request: Request):
return request.jwt_claims.get("sub")
def remember(self, request: Request, principal, **kw):
warnings.warn(
"JWT tokens need to be returned by an API. Using remember() "
"has no effect.",
stacklevel=3,
)
return []
def forget(self, request: Request):
warnings.warn(
"JWT tokens are managed by API (users) manually. Using forget() "
"has no effect.",
stacklevel=3,
)
return []
class ReissueError(Exception):
pass
@implementer(IAuthenticationPolicy)
class JWTCookieAuthenticationPolicy(JWTAuthenticationPolicy):
def __init__(
self,
private_key,
public_key=None,
algorithm="HS512",
leeway=0,
expiration=None,
default_claims=None,
http_header="Authorization",
auth_type="JWT",
callback=None,
json_encoder=None,
audience=None,
cookie_name=None,
https_only=True,
reissue_time=None,
cookie_path=None,
):
super(JWTCookieAuthenticationPolicy, self).__init__(
private_key,
public_key,
algorithm,
leeway,
expiration,
default_claims,
http_header,
auth_type,
callback,
json_encoder,
audience,
)
self.https_only = https_only
self.cookie_name = cookie_name or "Authorization"
self.max_age = self.expiration and self.expiration.total_seconds()
self.cookie_path = cookie_path
if reissue_time and isinstance(reissue_time, datetime.timedelta):
reissue_time = reissue_time.total_seconds()
self.reissue_time = reissue_time
self.cookie_profile = CookieProfile(
cookie_name=self.cookie_name,
secure=self.https_only,
max_age=self.max_age,
httponly=True,
path=cookie_path,
)
@staticmethod
def make_from(policy, **kwargs):
if not isinstance(policy, JWTAuthenticationPolicy):
pol_type = policy.__class__.__name__
raise ValueError("Invalid policy type %s" % pol_type)
return JWTCookieAuthenticationPolicy(
private_key=policy.private_key,
public_key=policy.public_key,
algorithm=policy.algorithm,
leeway=policy.leeway,
expiration=policy.expiration,
default_claims=policy.default_claims,
http_header=policy.http_header,
auth_type=policy.auth_type,
callback=policy.callback,
json_encoder=policy.json_encoder,
audience=policy.audience,
**kwargs
)
def remember(self, request: Request, principal, **kw):
token = self.create_token(principal, self.expiration, self.audience, **kw)
if hasattr(request, "_jwt_cookie_reissued"):
request._jwt_cookie_reissue_revoked = True
request.response.set_cookie(
self.cookie_name,
token,
secure=self.https_only,
max_age=self.max_age,
httponly=True,
path=self.cookie_path,
domain=request.domain,
)
def forget(self, request: Request):
request._jwt_cookie_reissue_revoked = True
request.response.set_cookie(self.cookie_name, None)
def get_claims(self, request: Request):
# FIXME does not work. Store the token instead of using the cookie profile
profile = self.cookie_profile.bind(request)
cookie = profile.get_value()
reissue = self.reissue_time is not None
if cookie is None:
return {}
claims = self.jwt_decode(request, cookie)
if reissue and not hasattr(request, "_jwt_cookie_reissued"):
self._handle_reissue(request, claims)
return claims
def _handle_reissue(self, request: Request, claims: dict):
if not request or not claims:
raise ValueError("Cannot handle JWT reissue: insufficient arguments")
if "iat" not in claims:
raise ReissueError("Token claim's is missing IAT")
if "sub" not in claims:
raise ReissueError("Token claim's is missing SUB")
token_dt = claims["iat"]
principal = claims["sub"]
now = time.time()
if now < token_dt + self.reissue_time:
# Token not yet eligible for reissuing
return
extra_claims = dict(
filter(lambda item: item[0] not in self.jwt_std_claims, claims.items())
)
self.remember(request, principal, **extra_claims)
def reissue_jwt_cookie(re_request: Request):
if not hasattr(re_request, "_jwt_cookie_reissue_revoked"):
self.remember(re_request, principal, **extra_claims)
request.add_response_callback(reissue_jwt_cookie)
request._jwt_cookie_reissued = True