This repository was archived by the owner on May 26, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 656
/
Copy pathtest_authentication.py
294 lines (233 loc) · 10.9 KB
/
test_authentication.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
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
import unittest
import uuid
from .models import CustomUser
from .utils import get_jwt_secret
from django.test.utils import override_settings
from django.test import TestCase
from rest_framework import status
try:
try:
from rest_framework_oauth.compat import oauth2_provider
from rest_framework_oauth.compat.oauth2_provider import oauth2
except ImportError:
# if oauth2 module can not be imported, skip the tests,
# because models have not been initialized.
oauth2_provider = None
except ImportError:
try:
from rest_framework.compat import oauth2_provider
from rest_framework.compat.oauth2_provider import oauth2 # NOQA
except ImportError:
# if oauth2 module can not be imported, skip the tests,
# because models have not been initialized.
oauth2_provider = None
from rest_framework.test import APIClient
from rest_framework.test import APIRequestFactory
from rest_framework_jwt import utils
from rest_framework_jwt.compat import get_user_model
from rest_framework_jwt.settings import DEFAULTS
from rest_framework_jwt.settings import api_settings
User = get_user_model()
DJANGO_OAUTH2_PROVIDER_NOT_INSTALLED = 'django-oauth2-provider not installed'
factory = APIRequestFactory()
class JSONWebTokenAuthenticationTests(TestCase):
"""JSON Web Token Authentication"""
def setUp(self):
self.csrf_client = APIClient(enforce_csrf_checks=True)
self.username = 'jpueblo'
self.email = '[email protected]'
self.user = User.objects.create_user(self.username, self.email)
def test_post_form_passing_jwt_auth(self):
"""
Ensure POSTing form over JWT auth with correct credentials
passes and does not require CSRF
"""
payload = utils.jwt_payload_handler(self.user)
token = utils.jwt_encode_handler(payload)
auth = 'JWT {0}'.format(token)
response = self.csrf_client.post(
'/jwt/', {'example': 'example'}, HTTP_AUTHORIZATION=auth)
self.assertEqual(response.status_code, status.HTTP_200_OK)
self.assertEqual(response.content, b'mockview-post')
# Ensure `authenticate` returned the decoded payload.
self.assertEqual(response.wsgi_request.user, self.user)
payload = response.wsgi_request.auth
self.assertIsInstance(payload, dict)
self.assertEqual(set(payload.keys()), {
'user_id', 'username', 'exp', 'email'})
def test_post_json_passing_jwt_auth(self):
"""
Ensure POSTing JSON over JWT auth with correct credentials
passes and does not require CSRF
"""
payload = utils.jwt_payload_handler(self.user)
token = utils.jwt_encode_handler(payload)
auth = 'JWT {0}'.format(token)
response = self.csrf_client.post(
'/jwt/', {'example': 'example'},
HTTP_AUTHORIZATION=auth, format='json')
self.assertEqual(response.status_code, status.HTTP_200_OK)
def test_post_form_failing_jwt_auth(self):
"""
Ensure POSTing form over JWT auth without correct credentials fails
"""
response = self.csrf_client.post('/jwt/', {'example': 'example'})
self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)
self.assertEqual(response['WWW-Authenticate'], 'JWT realm="api"')
def test_post_json_failing_jwt_auth(self):
"""
Ensure POSTing json over JWT auth without correct credentials fails
"""
response = self.csrf_client.post('/jwt/', {'example': 'example'},
format='json')
self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)
self.assertEqual(response['WWW-Authenticate'], 'JWT realm="api"')
def test_post_no_jwt_header_failing_jwt_auth(self):
"""
Ensure POSTing over JWT auth without credentials fails
"""
auth = 'JWT'
response = self.csrf_client.post(
'/jwt/', {'example': 'example'},
HTTP_AUTHORIZATION=auth, format='json')
msg = 'Invalid Authorization header. No credentials provided.'
self.assertEqual(response.data['detail'], msg)
self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)
self.assertEqual(response['WWW-Authenticate'], 'JWT realm="api"')
def test_post_invalid_jwt_header_failing_jwt_auth(self):
"""
Ensure POSTing over JWT auth without correct credentials fails
"""
auth = 'JWT abc abc'
response = self.csrf_client.post(
'/jwt/', {'example': 'example'},
HTTP_AUTHORIZATION=auth, format='json')
msg = ('Invalid Authorization header. Credentials string '
'should not contain spaces.')
self.assertEqual(response.data['detail'], msg)
self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)
self.assertEqual(response['WWW-Authenticate'], 'JWT realm="api"')
def test_post_expired_token_failing_jwt_auth(self):
"""
Ensure POSTing over JWT auth with expired token fails
"""
payload = utils.jwt_payload_handler(self.user)
payload['exp'] = 1
token = utils.jwt_encode_handler(payload)
auth = 'JWT {0}'.format(token)
response = self.csrf_client.post(
'/jwt/', {'example': 'example'},
HTTP_AUTHORIZATION=auth, format='json')
msg = 'Signature has expired.'
self.assertEqual(response.data['detail'], msg)
self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)
self.assertEqual(response['WWW-Authenticate'], 'JWT realm="api"')
@override_settings(AUTH_USER_MODEL='tests.CustomUser')
def test_post_form_failing_jwt_auth_changed_user_secret_key(self):
"""
Ensure changin secret key on USER level makes tokens invalid
"""
# fine tune settings
api_settings.JWT_GET_USER_SECRET_KEY = get_jwt_secret
tmp_user = CustomUser.objects.create(email='[email protected]')
payload = utils.jwt_payload_handler(tmp_user)
token = utils.jwt_encode_handler(payload)
auth = 'JWT {0}'.format(token)
response = self.csrf_client.post(
'/jwt/', {'example': 'example'}, HTTP_AUTHORIZATION=auth, format='json')
self.assertEqual(response.status_code, status.HTTP_200_OK)
# change token, verify
tmp_user.jwt_secret = uuid.uuid4()
tmp_user.save()
response = self.csrf_client.post(
'/jwt/', {'example': 'example'}, HTTP_AUTHORIZATION=auth)
self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)
# revert api settings
api_settings.JWT_GET_USER_SECRET_KEY = DEFAULTS['JWT_GET_USER_SECRET_KEY']
def test_post_invalid_token_failing_jwt_auth(self):
"""
Ensure POSTing over JWT auth with invalid token fails
"""
auth = 'JWT abc123'
response = self.csrf_client.post(
'/jwt/', {'example': 'example'},
HTTP_AUTHORIZATION=auth, format='json')
msg = 'Error decoding signature.'
self.assertEqual(response.data['detail'], msg)
self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)
self.assertEqual(response['WWW-Authenticate'], 'JWT realm="api"')
@unittest.skipUnless(oauth2_provider, DJANGO_OAUTH2_PROVIDER_NOT_INSTALLED)
def test_post_passing_jwt_auth_with_oauth2_priority(self):
"""
Ensure POSTing over JWT auth with correct credentials
passes and does not require CSRF when OAuth2Authentication
has priority on authentication_classes
"""
payload = utils.jwt_payload_handler(self.user)
token = utils.jwt_encode_handler(payload)
auth = 'JWT {0}'.format(token)
response = self.csrf_client.post(
'/oauth2-jwt/', {'example': 'example'},
HTTP_AUTHORIZATION=auth, format='json')
self.assertEqual(response.status_code, status.HTTP_200_OK, response)
@unittest.skipUnless(oauth2_provider, DJANGO_OAUTH2_PROVIDER_NOT_INSTALLED)
def test_post_passing_oauth2_with_jwt_auth_priority(self):
"""
Ensure POSTing over OAuth2 with correct credentials
passes and does not require CSRF when JSONWebTokenAuthentication
has priority on authentication_classes
"""
Client = oauth2_provider.oauth2.models.Client
AccessToken = oauth2_provider.oauth2.models.AccessToken
oauth2_client = Client.objects.create(
user=self.user,
client_type=0,
)
access_token = AccessToken.objects.create(
user=self.user,
client=oauth2_client,
)
auth = 'Bearer {0}'.format(access_token.token)
response = self.csrf_client.post(
'/jwt-oauth2/', {'example': 'example'},
HTTP_AUTHORIZATION=auth, format='json')
self.assertEqual(response.status_code, status.HTTP_200_OK, response)
def test_post_form_passing_jwt_invalid_payload(self):
"""
Ensure POSTing json over JWT auth with invalid payload fails
"""
payload = dict(email=None)
token = utils.jwt_encode_handler(payload)
auth = 'JWT {0}'.format(token)
response = self.csrf_client.post(
'/jwt/', {'example': 'example'}, HTTP_AUTHORIZATION=auth)
msg = 'Invalid payload.'
self.assertEqual(response.data['detail'], msg)
self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)
def test_different_auth_header_prefix(self):
"""
Ensure using a different setting for `JWT_AUTH_HEADER_PREFIX` and
with correct credentials passes.
"""
api_settings.JWT_AUTH_HEADER_PREFIX = 'Bearer'
payload = utils.jwt_payload_handler(self.user)
token = utils.jwt_encode_handler(payload)
auth = 'Bearer {0}'.format(token)
response = self.csrf_client.post(
'/jwt/', {'example': 'example'},
HTTP_AUTHORIZATION=auth, format='json')
self.assertEqual(response.status_code, status.HTTP_200_OK)
# Restore original settings
api_settings.JWT_AUTH_HEADER_PREFIX = DEFAULTS['JWT_AUTH_HEADER_PREFIX']
def test_post_form_failing_jwt_auth_different_auth_header_prefix(self):
"""
Ensure using a different setting for `JWT_AUTH_HEADER_PREFIX` and
POSTing form over JWT auth without correct credentials fails and
generated correct WWW-Authenticate header
"""
api_settings.JWT_AUTH_HEADER_PREFIX = 'Bearer'
response = self.csrf_client.post('/jwt/', {'example': 'example'})
self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)
self.assertEqual(response['WWW-Authenticate'], 'Bearer realm="api"')
# Restore original settings
api_settings.JWT_AUTH_HEADER_PREFIX = DEFAULTS['JWT_AUTH_HEADER_PREFIX']