|
1 | 1 | import unittest |
| 2 | +import uuid |
| 3 | + |
| 4 | +from .models import CustomUser |
| 5 | + |
| 6 | +from .utils import get_jwt_secret |
| 7 | +from django.test.utils import override_settings |
2 | 8 |
|
3 | 9 | from django.test import TestCase |
4 | 10 | from rest_framework import status |
|
19 | 25 | # because models have not been initialized. |
20 | 26 | oauth2_provider = None |
21 | 27 |
|
22 | | -from rest_framework.test import APIRequestFactory, APIClient |
| 28 | +from rest_framework.test import APIClient |
| 29 | +from rest_framework.test import APIRequestFactory |
23 | 30 |
|
24 | 31 | from rest_framework_jwt import utils |
25 | 32 | from rest_framework_jwt.compat import get_user_model |
26 | | -from rest_framework_jwt.settings import api_settings, DEFAULTS |
| 33 | +from rest_framework_jwt.settings import DEFAULTS |
| 34 | +from rest_framework_jwt.settings import api_settings |
27 | 35 |
|
28 | 36 | User = get_user_model() |
29 | 37 |
|
@@ -137,6 +145,36 @@ def test_post_expired_token_failing_jwt_auth(self): |
137 | 145 | self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED) |
138 | 146 | self.assertEqual(response['WWW-Authenticate'], 'JWT realm="api"') |
139 | 147 |
|
| 148 | + @override_settings(AUTH_USER_MODEL='tests.CustomUser') |
| 149 | + def test_post_form_failing_jwt_auth_changed_user_secret_key(self): |
| 150 | + """ |
| 151 | + Ensure changin secret key on USER level makes tokens invalid |
| 152 | + """ |
| 153 | + # fine tune settings |
| 154 | + api_settings.JWT_GET_USER_SECRET_KEY = get_jwt_secret |
| 155 | + |
| 156 | + tmp_user = CustomUser.objects.create(email='b@example.com') |
| 157 | + payload = utils.jwt_payload_handler(tmp_user) |
| 158 | + token = utils.jwt_encode_handler(payload) |
| 159 | + |
| 160 | + auth = 'JWT {0}'.format(token) |
| 161 | + response = self.csrf_client.post( |
| 162 | + '/jwt/', {'example': 'example'}, HTTP_AUTHORIZATION=auth, format='json') |
| 163 | + |
| 164 | + self.assertEqual(response.status_code, status.HTTP_200_OK) |
| 165 | + |
| 166 | + # change token, verify |
| 167 | + tmp_user.jwt_secret = uuid.uuid4() |
| 168 | + tmp_user.save() |
| 169 | + |
| 170 | + response = self.csrf_client.post( |
| 171 | + '/jwt/', {'example': 'example'}, HTTP_AUTHORIZATION=auth) |
| 172 | + |
| 173 | + self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED) |
| 174 | + |
| 175 | + # revert api settings |
| 176 | + api_settings.JWT_GET_USER_SECRET_KEY = DEFAULTS['JWT_GET_USER_SECRET_KEY'] |
| 177 | + |
140 | 178 | def test_post_invalid_token_failing_jwt_auth(self): |
141 | 179 | """ |
142 | 180 | Ensure POSTing over JWT auth with invalid token fails |
|
0 commit comments