| 1 |
import base64 |
| 2 |
|
| 3 |
import pytest |
| 4 |
from django.conf import settings |
| 5 |
from django.contrib.auth.models import User |
| 6 |
from django.http import HttpResponse |
| 7 |
from django.test import TestCase, override_settings |
| 8 |
from django.urls import include, path |
| 9 |
|
| 10 |
from rest_framework import ( |
| 11 |
HTTP_HEADER_ENCODING, exceptions, permissions, renderers, status |
| 12 |
) |
| 13 |
from rest_framework.authentication import ( |
| 14 |
BaseAuthentication, BasicAuthentication, RemoteUserAuthentication, |
| 15 |
SessionAuthentication, TokenAuthentication |
| 16 |
) |
| 17 |
from rest_framework.authtoken.models import Token |
| 18 |
from rest_framework.authtoken.views import obtain_auth_token |
| 19 |
from rest_framework.response import Response |
| 20 |
from rest_framework.test import APIClient, APIRequestFactory |
| 21 |
from rest_framework.views import APIView |
| 22 |
|
| 23 |
from .models import CustomToken |
| 24 |
|
| 25 |
factory = APIRequestFactory() |
| 26 |
|
| 27 |
|
| 28 |
class CustomTokenAuthentication(TokenAuthentication): |
| 29 |
model = CustomToken |
| 30 |
|
| 31 |
|
| 32 |
class CustomKeywordTokenAuthentication(TokenAuthentication): |
| 33 |
keyword = 'Bearer' |
| 34 |
|
| 35 |
|
| 36 |
class MockView(APIView): |
| 37 |
permission_classes = (permissions.IsAuthenticated,) |
| 38 |
|
| 39 |
def get(self, request): |
| 40 |
return HttpResponse({'a': 1, 'b': 2, 'c': 3}) |
| 41 |
|
| 42 |
def post(self, request): |
| 43 |
return HttpResponse({'a': 1, 'b': 2, 'c': 3}) |
| 44 |
|
| 45 |
def put(self, request): |
| 46 |
return HttpResponse({'a': 1, 'b': 2, 'c': 3}) |
| 47 |
|
| 48 |
|
| 49 |
urlpatterns = [ |
| 50 |
path( |
| 51 |
'session/', |
| 52 |
MockView.as_view(authentication_classes=[SessionAuthentication]) |
| 53 |
), |
| 54 |
path( |
| 55 |
'basic/', |
| 56 |
MockView.as_view(authentication_classes=[BasicAuthentication]) |
| 57 |
), |
| 58 |
path( |
| 59 |
'remote-user/', |
| 60 |
MockView.as_view(authentication_classes=[RemoteUserAuthentication]) |
| 61 |
), |
| 62 |
path( |
| 63 |
'token/', |
| 64 |
MockView.as_view(authentication_classes=[TokenAuthentication]) |
| 65 |
), |
| 66 |
path( |
| 67 |
'customtoken/', |
| 68 |
MockView.as_view(authentication_classes=[CustomTokenAuthentication]) |
| 69 |
), |
| 70 |
path( |
| 71 |
'customkeywordtoken/', |
| 72 |
MockView.as_view( |
| 73 |
authentication_classes=[CustomKeywordTokenAuthentication] |
| 74 |
) |
| 75 |
), |
| 76 |
path('auth-token/', obtain_auth_token), |
| 77 |
path('auth/', include('rest_framework.urls', namespace='rest_framework')), |
| 78 |
] |
| 79 |
|
| 80 |
|
| 81 |
@override_settings(ROOT_URLCONF=__name__) |
| 82 |
class BasicAuthTests(TestCase): |
| 83 |
"""Basic authentication""" |
| 84 |
|
| 85 |
def setUp(self): |
| 86 |
self.csrf_client = APIClient(enforce_csrf_checks=True) |
| 87 |
self.username = 'john' |
| 88 |
self.email = '[email protected]' |
| 89 |
self.password = 'password' |
| 90 |
self.user = User.objects.create_user( |
| 91 |
self.username, self.email, self.password |
| 92 |
) |
| 93 |
|
| 94 |
def test_post_form_passing_basic_auth(self): |
| 95 |
"""Ensure POSTing json over basic auth with correct credentials passes and does not require CSRF""" |
| 96 |
credentials = ('%s:%s' % (self.username, self.password)) |
| 97 |
base64_credentials = base64.b64encode( |
| 98 |
credentials.encode(HTTP_HEADER_ENCODING) |
| 99 |
).decode(HTTP_HEADER_ENCODING) |
| 100 |
auth = 'Basic %s' % base64_credentials |
| 101 |
response = self.csrf_client.post( |
| 102 |
'/basic/', |
| 103 |
{'example': 'example'}, |
| 104 |
HTTP_AUTHORIZATION=auth |
| 105 |
) |
| 106 |
assert response.status_code == status.HTTP_200_OK |
| 107 |
|
| 108 |
def test_post_json_passing_basic_auth(self): |
| 109 |
"""Ensure POSTing form over basic auth with correct credentials passes and does not require CSRF""" |
| 110 |
credentials = ('%s:%s' % (self.username, self.password)) |
| 111 |
base64_credentials = base64.b64encode( |
| 112 |
credentials.encode(HTTP_HEADER_ENCODING) |
| 113 |
).decode(HTTP_HEADER_ENCODING) |
| 114 |
auth = 'Basic %s' % base64_credentials |
| 115 |
response = self.csrf_client.post( |
| 116 |
'/basic/', |
| 117 |
{'example': 'example'}, |
| 118 |
format='json', |
| 119 |
HTTP_AUTHORIZATION=auth |
| 120 |
) |
| 121 |
assert response.status_code == status.HTTP_200_OK |
| 122 |
|
| 123 |
def test_post_json_without_password_failing_basic_auth(self): |
| 124 |
"""Ensure POSTing json without password (even if password is empty string) returns 401""" |
| 125 |
self.user.set_password("") |
| 126 |
credentials = ('%s' % (self.username)) |
| 127 |
base64_credentials = base64.b64encode( |
| 128 |
credentials.encode(HTTP_HEADER_ENCODING) |
| 129 |
).decode(HTTP_HEADER_ENCODING) |
| 130 |
auth = 'Basic %s' % base64_credentials |
| 131 |
response = self.csrf_client.post( |
| 132 |
'/basic/', |
| 133 |
{'example': 'example'}, |
| 134 |
format='json', |
| 135 |
HTTP_AUTHORIZATION=auth |
| 136 |
) |
| 137 |
assert response.status_code == status.HTTP_401_UNAUTHORIZED |
| 138 |
|
| 139 |
def test_regression_handle_bad_base64_basic_auth_header(self): |
| 140 |
"""Ensure POSTing JSON over basic auth with incorrectly padded Base64 string is handled correctly""" |
| 141 |
# regression test for issue in 'rest_framework.authentication.BasicAuthentication.authenticate' |
| 142 |
# https://github.com/encode/django-rest-framework/issues/4089 |
| 143 |
auth = 'Basic =a=' |
| 144 |
response = self.csrf_client.post( |
| 145 |
'/basic/', |
| 146 |
{'example': 'example'}, |
| 147 |
format='json', |
| 148 |
HTTP_AUTHORIZATION=auth |
| 149 |
) |
| 150 |
assert response.status_code == status.HTTP_401_UNAUTHORIZED |
| 151 |
|
| 152 |
def test_post_form_failing_basic_auth(self): |
| 153 |
"""Ensure POSTing form over basic auth without correct credentials fails""" |
| 154 |
response = self.csrf_client.post('/basic/', {'example': 'example'}) |
| 155 |
assert response.status_code == status.HTTP_401_UNAUTHORIZED |
| 156 |
|
| 157 |
def test_post_json_failing_basic_auth(self): |
| 158 |
"""Ensure POSTing json over basic auth without correct credentials fails""" |
| 159 |
response = self.csrf_client.post( |
| 160 |
'/basic/', |
| 161 |
{'example': 'example'}, |
| 162 |
format='json' |
| 163 |
) |
| 164 |
assert response.status_code == status.HTTP_401_UNAUTHORIZED |
| 165 |
assert response['WWW-Authenticate'] == 'Basic realm="api"' |
| 166 |
|
| 167 |
def test_fail_post_if_credentials_are_missing(self): |
| 168 |
response = self.csrf_client.post( |
| 169 |
'/basic/', {'example': 'example'}, HTTP_AUTHORIZATION='Basic ') |
| 170 |
assert response.status_code == status.HTTP_401_UNAUTHORIZED |
| 171 |
|
| 172 |
def test_fail_post_if_credentials_contain_spaces(self): |
| 173 |
response = self.csrf_client.post( |
| 174 |
'/basic/', {'example': 'example'}, |
| 175 |
HTTP_AUTHORIZATION='Basic foo bar' |
| 176 |
) |
| 177 |
assert response.status_code == status.HTTP_401_UNAUTHORIZED |
| 178 |
|
| 179 |
def test_decoding_of_utf8_credentials(self): |
| 180 |
username = 'walterwhité' |
| 181 |
email = '[email protected]' |
| 182 |
password = 'pässwörd' |
| 183 |
User.objects.create_user( |
| 184 |
username, email, password |
| 185 |
) |
| 186 |
credentials = ('%s:%s' % (username, password)) |
| 187 |
base64_credentials = base64.b64encode( |
| 188 |
credentials.encode('utf-8') |
| 189 |
).decode(HTTP_HEADER_ENCODING) |
| 190 |
auth = 'Basic %s' % base64_credentials |
| 191 |
response = self.csrf_client.post( |
| 192 |
'/basic/', |
| 193 |
{'example': 'example'}, |
| 194 |
HTTP_AUTHORIZATION=auth |
| 195 |
) |
| 196 |
assert response.status_code == status.HTTP_200_OK |
| 197 |
|
| 198 |
|
| 199 |
@override_settings(ROOT_URLCONF=__name__) |
| 200 |
class SessionAuthTests(TestCase): |
| 201 |
"""User session authentication""" |
| 202 |
|
| 203 |
def setUp(self): |
| 204 |
self.csrf_client = APIClient(enforce_csrf_checks=True) |
| 205 |
self.non_csrf_client = APIClient(enforce_csrf_checks=False) |
| 206 |
self.username = 'john' |
| 207 |
self.email = '[email protected]' |
| 208 |
self.password = 'password' |
| 209 |
self.user = User.objects.create_user( |
| 210 |
self.username, self.email, self.password |
| 211 |
) |
| 212 |
|
| 213 |
def tearDown(self): |
| 214 |
self.csrf_client.logout() |
| 215 |
|
| 216 |
def test_login_view_renders_on_get(self): |
| 217 |
""" |
| 218 |
Ensure the login template renders for a basic GET. |
| 219 |
|
| 220 |
cf. [#1810](https://github.com/encode/django-rest-framework/pull/1810) |
| 221 |
""" |
| 222 |
response = self.csrf_client.get('/auth/login/') |
| 223 |
content = response.content.decode() |
| 224 |
assert '<label for="id_username">Username:</label>' in content |
| 225 |
|
| 226 |
def test_post_form_session_auth_failing_csrf(self): |
| 227 |
""" |
| 228 |
Ensure POSTing form over session authentication without CSRF token fails. |
| 229 |
""" |
| 230 |
self.csrf_client.login(username=self.username, password=self.password) |
| 231 |
response = self.csrf_client.post('/session/', {'example': 'example'}) |
| 232 |
assert response.status_code == status.HTTP_403_FORBIDDEN |
| 233 |
|
| 234 |
def test_post_form_session_auth_passing_csrf(self): |
| 235 |
""" |
| 236 |
Ensure POSTing form over session authentication with CSRF token succeeds. |
| 237 |
Regression test for #6088 |
| 238 |
""" |
| 239 |
self.csrf_client.login(username=self.username, password=self.password) |
| 240 |
|
| 241 |
# Set the csrf_token cookie so that CsrfViewMiddleware._get_token() works |
| 242 |
from django.middleware.csrf import ( |
| 243 |
_get_new_csrf_string, _mask_cipher_secret |
| 244 |
) |
| 245 |
token = _mask_cipher_secret(_get_new_csrf_string()) |
| 246 |
self.csrf_client.cookies[settings.CSRF_COOKIE_NAME] = token |
| 247 |
|
| 248 |
# Post the token matching the cookie value |
| 249 |
response = self.csrf_client.post('/session/', { |
| 250 |
'example': 'example', |
| 251 |
'csrfmiddlewaretoken': token, |
| 252 |
}) |
| 253 |
assert response.status_code == status.HTTP_200_OK |
| 254 |
|
| 255 |
def test_post_form_session_auth_passing(self): |
| 256 |
""" |
| 257 |
Ensure POSTing form over session authentication with logged in |
| 258 |
user and CSRF token passes. |
| 259 |
""" |
| 260 |
self.non_csrf_client.login( |
| 261 |
username=self.username, password=self.password |
| 262 |
) |
| 263 |
response = self.non_csrf_client.post( |
| 264 |
'/session/', {'example': 'example'} |
| 265 |
) |
| 266 |
assert response.status_code == status.HTTP_200_OK |
| 267 |
|
| 268 |
def test_put_form_session_auth_passing(self): |
| 269 |
""" |
| 270 |
Ensure PUTting form over session authentication with |
| 271 |
logged in user and CSRF token passes. |
| 272 |
""" |
| 273 |
self.non_csrf_client.login( |
| 274 |
username=self.username, password=self.password |
| 275 |
) |
| 276 |
response = self.non_csrf_client.put( |
| 277 |
'/session/', {'example': 'example'} |
| 278 |
) |
| 279 |
assert response.status_code == status.HTTP_200_OK |
| 280 |
|
| 281 |
def test_post_form_session_auth_failing(self): |
| 282 |
""" |
| 283 |
Ensure POSTing form over session authentication without logged in user fails. |
| 284 |
""" |
| 285 |
response = self.csrf_client.post('/session/', {'example': 'example'}) |
| 286 |
assert response.status_code == status.HTTP_403_FORBIDDEN |
| 287 |
|
| 288 |
|
| 289 |
class BaseTokenAuthTests: |
| 290 |
"""Token authentication""" |
| 291 |
model = None |
| 292 |
path = None |
| 293 |
header_prefix = 'Token ' |
| 294 |
|
| 295 |
def setUp(self): |
| 296 |
self.csrf_client = APIClient(enforce_csrf_checks=True) |
| 297 |
self.username = 'john' |
| 298 |
self.email = '[email protected]' |
| 299 |
self.password = 'password' |
| 300 |
self.user = User.objects.create_user( |
| 301 |
self.username, self.email, self.password |
| 302 |
) |
| 303 |
|
| 304 |
self.key = 'abcd1234' |
| 305 |
self.token = self.model.objects.create(key=self.key, user=self.user) |
| 306 |
|
| 307 |
def test_post_form_passing_token_auth(self): |
| 308 |
""" |
| 309 |
Ensure POSTing json over token auth with correct |
| 310 |
credentials passes and does not require CSRF |
| 311 |
""" |
| 312 |
auth = self.header_prefix + self.key |
| 313 |
response = self.csrf_client.post( |
| 314 |
self.path, {'example': 'example'}, HTTP_AUTHORIZATION=auth |
| 315 |
) |
| 316 |
assert response.status_code == status.HTTP_200_OK |
| 317 |
|
| 318 |
def test_fail_authentication_if_user_is_not_active(self): |
| 319 |
user = User.objects.create_user('foo', 'bar', 'baz') |
| 320 |
user.is_active = False |
| 321 |
user.save() |
| 322 |
self.model.objects.create(key='foobar_token', user=user) |
| 323 |
response = self.csrf_client.post( |
| 324 |
self.path, {'example': 'example'}, |
| 325 |
HTTP_AUTHORIZATION=self.header_prefix + 'foobar_token' |
| 326 |
) |
| 327 |
assert response.status_code == status.HTTP_401_UNAUTHORIZED |
| 328 |
|
| 329 |
def test_fail_post_form_passing_nonexistent_token_auth(self): |
| 330 |
# use a nonexistent token key |
| 331 |
auth = self.header_prefix + 'wxyz6789' |
| 332 |
response = self.csrf_client.post( |
| 333 |
self.path, {'example': 'example'}, HTTP_AUTHORIZATION=auth |
| 334 |
) |
| 335 |
assert response.status_code == status.HTTP_401_UNAUTHORIZED |
| 336 |
|
| 337 |
def test_fail_post_if_token_is_missing(self): |
| 338 |
response = self.csrf_client.post( |
| 339 |
self.path, {'example': 'example'}, |
| 340 |
HTTP_AUTHORIZATION=self.header_prefix) |
| 341 |
assert response.status_code == status.HTTP_401_UNAUTHORIZED |
| 342 |
|
| 343 |
def test_fail_post_if_token_contains_spaces(self): |
| 344 |
response = self.csrf_client.post( |
| 345 |
self.path, {'example': 'example'}, |
| 346 |
HTTP_AUTHORIZATION=self.header_prefix + 'foo bar' |
| 347 |
) |
| 348 |
assert response.status_code == status.HTTP_401_UNAUTHORIZED |
| 349 |
|
| 350 |
def test_fail_post_form_passing_invalid_token_auth(self): |
| 351 |
# add an 'invalid' unicode character |
| 352 |
auth = self.header_prefix + self.key + "¸" |
| 353 |
response = self.csrf_client.post( |
| 354 |
self.path, {'example': 'example'}, HTTP_AUTHORIZATION=auth |
| 355 |
) |
| 356 |
assert response.status_code == status.HTTP_401_UNAUTHORIZED |
| 357 |
|
| 358 |
def test_post_json_passing_token_auth(self): |
| 359 |
""" |
| 360 |
Ensure POSTing form over token auth with correct |
| 361 |
credentials passes and does not require CSRF |
| 362 |
""" |
| 363 |
auth = self.header_prefix + self.key |
| 364 |
response = self.csrf_client.post( |
| 365 |
self.path, {'example': 'example'}, |
| 366 |
format='json', HTTP_AUTHORIZATION=auth |
| 367 |
) |
| 368 |
assert response.status_code == status.HTTP_200_OK |
| 369 |
|
| 370 |
def test_post_json_makes_one_db_query(self): |
| 371 |
""" |
| 372 |
Ensure that authenticating a user using a |
| 373 |
token performs only one DB query |
| 374 |
""" |
| 375 |
auth = self.header_prefix + self.key |
| 376 |
|
| 377 |
def func_to_test(): |
| 378 |
return self.csrf_client.post( |
| 379 |
self.path, {'example': 'example'}, |
| 380 |
format='json', HTTP_AUTHORIZATION=auth |
| 381 |
) |
| 382 |
|
| 383 |
self.assertNumQueries(1, func_to_test) |
| 384 |
|
| 385 |
def test_post_form_failing_token_auth(self): |
| 386 |
""" |
| 387 |
Ensure POSTing form over token auth without correct credentials fails |
| 388 |
""" |
| 389 |
response = self.csrf_client.post(self.path, {'example': 'example'}) |
| 390 |
assert response.status_code == status.HTTP_401_UNAUTHORIZED |
| 391 |
|
| 392 |
def test_post_json_failing_token_auth(self): |
| 393 |
""" |
| 394 |
Ensure POSTing json over token auth without correct credentials fails |
| 395 |
""" |
| 396 |
response = self.csrf_client.post( |
| 397 |
self.path, {'example': 'example'}, format='json' |
| 398 |
) |
| 399 |
assert response.status_code == status.HTTP_401_UNAUTHORIZED |
| 400 |
|
| 401 |
|
| 402 |
@override_settings(ROOT_URLCONF=__name__) |
| 403 |
class TokenAuthTests(BaseTokenAuthTests, TestCase): |
| 404 |
model = Token |
| 405 |
path = '/token/' |
| 406 |
|
| 407 |
def test_token_has_auto_assigned_key_if_none_provided(self): |
| 408 |
"""Ensure creating a token with no key will auto-assign a key""" |
| 409 |
self.token.delete() |
| 410 |
token = self.model.objects.create(user=self.user) |
| 411 |
assert bool(token.key) |
| 412 |
|
| 413 |
def test_generate_key_returns_string(self): |
| 414 |
"""Ensure generate_key returns a string""" |
| 415 |
token = self.model() |
| 416 |
key = token.generate_key() |
| 417 |
assert isinstance(key, str) |
| 418 |
|
| 419 |
def test_generate_key_accessible_as_classmethod(self): |
| 420 |
key = self.model.generate_key() |
| 421 |
assert isinstance(key, str) |
| 422 |
|
| 423 |
def test_generate_key_returns_valid_format(self): |
| 424 |
"""Ensure generate_key returns a valid token format""" |
| 425 |
key = self.model.generate_key() |
| 426 |
assert len(key) == 40 |
| 427 |
# Should contain only valid hexadecimal characters |
| 428 |
assert all(c in '0123456789abcdef' for c in key) |
| 429 |
|
| 430 |
def test_generate_key_produces_unique_values(self): |
| 431 |
"""Ensure generate_key produces unique values across multiple calls""" |
| 432 |
keys = set() |
| 433 |
for _ in range(100): |
| 434 |
key = self.model.generate_key() |
| 435 |
assert key not in keys, f"Duplicate key generated: {key}" |
| 436 |
keys.add(key) |
| 437 |
|
| 438 |
def test_generate_key_collision_resistance(self): |
| 439 |
"""Test collision resistance with reasonable sample size""" |
| 440 |
keys = set() |
| 441 |
for _ in range(500): |
| 442 |
key = self.model.generate_key() |
| 443 |
assert key not in keys, f"Collision found: {key}" |
| 444 |
keys.add(key) |
| 445 |
assert len(keys) == 500, f"Expected 500 unique keys, got {len(keys)}" |
| 446 |
|
| 447 |
def test_generate_key_randomness_quality(self): |
| 448 |
"""Test basic randomness properties of generated keys""" |
| 449 |
keys = [self.model.generate_key() for _ in range(10)] |
| 450 |
# Consecutive keys should be different |
| 451 |
for i in range(len(keys) - 1): |
| 452 |
assert keys[i] != keys[i + 1], "Consecutive keys should be different" |
| 453 |
# Keys should not follow obvious patterns |
| 454 |
for key in keys: |
| 455 |
# Should not be all same character |
| 456 |
assert not all(c == key[0] for c in key), f"Key has all same characters: {key}" |
| 457 |
|
| 458 |
def test_token_login_json(self): |
| 459 |
"""Ensure token login view using JSON POST works.""" |
| 460 |
client = APIClient(enforce_csrf_checks=True) |
| 461 |
response = client.post( |
| 462 |
'/auth-token/', |
| 463 |
{'username': self.username, 'password': self.password}, |
| 464 |
format='json' |
| 465 |
) |
| 466 |
assert response.status_code == status.HTTP_200_OK |
| 467 |
assert response.data['token'] == self.key |
| 468 |
|
| 469 |
def test_token_login_json_bad_creds(self): |
| 470 |
""" |
| 471 |
Ensure token login view using JSON POST fails if |
| 472 |
bad credentials are used |
| 473 |
""" |
| 474 |
client = APIClient(enforce_csrf_checks=True) |
| 475 |
response = client.post( |
| 476 |
'/auth-token/', |
| 477 |
{'username': self.username, 'password': "badpass"}, |
| 478 |
format='json' |
| 479 |
) |
| 480 |
assert response.status_code == 400 |
| 481 |
|
| 482 |
def test_token_login_json_missing_fields(self): |
| 483 |
"""Ensure token login view using JSON POST fails if missing fields.""" |
| 484 |
client = APIClient(enforce_csrf_checks=True) |
| 485 |
response = client.post('/auth-token/', |
| 486 |
{'username': self.username}, format='json') |
| 487 |
assert response.status_code == 400 |
| 488 |
|
| 489 |
def test_token_login_form(self): |
| 490 |
"""Ensure token login view using form POST works.""" |
| 491 |
client = APIClient(enforce_csrf_checks=True) |
| 492 |
response = client.post( |
| 493 |
'/auth-token/', |
| 494 |
{'username': self.username, 'password': self.password} |
| 495 |
) |
| 496 |
assert response.status_code == status.HTTP_200_OK |
| 497 |
assert response.data['token'] == self.key |
| 498 |
|
| 499 |
|
| 500 |
@override_settings(ROOT_URLCONF=__name__) |
| 501 |
class CustomTokenAuthTests(BaseTokenAuthTests, TestCase): |
| 502 |
model = CustomToken |
| 503 |
path = '/customtoken/' |
| 504 |
|
| 505 |
|
| 506 |
@override_settings(ROOT_URLCONF=__name__) |
| 507 |
class CustomKeywordTokenAuthTests(BaseTokenAuthTests, TestCase): |
| 508 |
model = Token |
| 509 |
path = '/customkeywordtoken/' |
| 510 |
header_prefix = 'Bearer ' |
| 511 |
|
| 512 |
|
| 513 |
class IncorrectCredentialsTests(TestCase): |
| 514 |
def test_incorrect_credentials(self): |
| 515 |
""" |
| 516 |
If a request contains bad authentication credentials, then |
| 517 |
authentication should run and error, even if no permissions |
| 518 |
are set on the view. |
| 519 |
""" |
| 520 |
|
| 521 |
class IncorrectCredentialsAuth(BaseAuthentication): |
| 522 |
def authenticate(self, request): |
| 523 |
raise exceptions.AuthenticationFailed('Bad credentials') |
| 524 |
|
| 525 |
request = factory.get('/') |
| 526 |
view = MockView.as_view( |
| 527 |
authentication_classes=(IncorrectCredentialsAuth,), |
| 528 |
permission_classes=() |
| 529 |
) |
| 530 |
response = view(request) |
| 531 |
assert response.status_code == status.HTTP_403_FORBIDDEN |
| 532 |
assert response.data == {'detail': 'Bad credentials'} |
| 533 |
|
| 534 |
|
| 535 |
class FailingAuthAccessedInRenderer(TestCase): |
| 536 |
def setUp(self): |
| 537 |
class AuthAccessingRenderer(renderers.BaseRenderer): |
| 538 |
media_type = 'text/plain' |
| 539 |
format = 'txt' |
| 540 |
|
| 541 |
def render(self, data, media_type=None, renderer_context=None): |
| 542 |
request = renderer_context['request'] |
| 543 |
if request.user.is_authenticated: |
| 544 |
return b'authenticated' |
| 545 |
return b'not authenticated' |
| 546 |
|
| 547 |
class FailingAuth(BaseAuthentication): |
| 548 |
def authenticate(self, request): |
| 549 |
raise exceptions.AuthenticationFailed('authentication failed') |
| 550 |
|
| 551 |
class ExampleView(APIView): |
| 552 |
authentication_classes = (FailingAuth,) |
| 553 |
renderer_classes = (AuthAccessingRenderer,) |
| 554 |
|
| 555 |
def get(self, request): |
| 556 |
return Response({'foo': 'bar'}) |
| 557 |
|
| 558 |
self.view = ExampleView.as_view() |
| 559 |
|
| 560 |
def test_failing_auth_accessed_in_renderer(self): |
| 561 |
""" |
| 562 |
When authentication fails the renderer should still be able to access |
| 563 |
`request.user` without raising an exception. Particularly relevant |
| 564 |
to HTML responses that might reasonably access `request.user`. |
| 565 |
""" |
| 566 |
request = factory.get('/') |
| 567 |
response = self.view(request) |
| 568 |
content = response.render().content |
| 569 |
assert content == b'not authenticated' |
| 570 |
|
| 571 |
|
| 572 |
class NoAuthenticationClassesTests(TestCase): |
| 573 |
def test_permission_message_with_no_authentication_classes(self): |
| 574 |
""" |
| 575 |
An unauthenticated request made against a view that contains no |
| 576 |
`authentication_classes` but do contain `permissions_classes` the error |
| 577 |
code returned should be 403 with the exception's message. |
| 578 |
""" |
| 579 |
|
| 580 |
class DummyPermission(permissions.BasePermission): |
| 581 |
message = 'Dummy permission message' |
| 582 |
|
| 583 |
def has_permission(self, request, view): |
| 584 |
return False |
| 585 |
|
| 586 |
request = factory.get('/') |
| 587 |
view = MockView.as_view( |
| 588 |
authentication_classes=(), |
| 589 |
permission_classes=(DummyPermission,), |
| 590 |
) |
| 591 |
response = view(request) |
| 592 |
assert response.status_code == status.HTTP_403_FORBIDDEN |
| 593 |
assert response.data == {'detail': 'Dummy permission message'} |
| 594 |
|
| 595 |
|
| 596 |
class BasicAuthenticationUnitTests(TestCase): |
| 597 |
|
| 598 |
def test_base_authentication_abstract_method(self): |
| 599 |
with pytest.raises(NotImplementedError): |
| 600 |
BaseAuthentication().authenticate({}) |
| 601 |
|
| 602 |
def test_basic_authentication_raises_error_if_user_not_found(self): |
| 603 |
auth = BasicAuthentication() |
| 604 |
with pytest.raises(exceptions.AuthenticationFailed): |
| 605 |
auth.authenticate_credentials('invalid id', 'invalid password') |
| 606 |
|
| 607 |
def test_basic_authentication_raises_error_if_user_not_active(self): |
| 608 |
from rest_framework import authentication |
| 609 |
|
| 610 |
class MockUser: |
| 611 |
is_active = False |
| 612 |
|
| 613 |
old_authenticate = authentication.authenticate |
| 614 |
authentication.authenticate = lambda **kwargs: MockUser() |
| 615 |
try: |
| 616 |
auth = authentication.BasicAuthentication() |
| 617 |
with pytest.raises(exceptions.AuthenticationFailed) as exc_info: |
| 618 |
auth.authenticate_credentials('foo', 'bar') |
| 619 |
assert 'User inactive or deleted.' in str(exc_info.value) |
| 620 |
finally: |
| 621 |
authentication.authenticate = old_authenticate |
| 622 |
|
| 623 |
|
| 624 |
@override_settings(ROOT_URLCONF=__name__, |
| 625 |
AUTHENTICATION_BACKENDS=('django.contrib.auth.backends.RemoteUserBackend',)) |
| 626 |
class RemoteUserAuthenticationUnitTests(TestCase): |
| 627 |
def setUp(self): |
| 628 |
self.username = 'john' |
| 629 |
self.email = '[email protected]' |
| 630 |
self.password = 'password' |
| 631 |
self.user = User.objects.create_user( |
| 632 |
self.username, self.email, self.password |
| 633 |
) |
| 634 |
|
| 635 |
def test_remote_user_works(self): |
| 636 |
response = self.client.post('/remote-user/', |
| 637 |
REMOTE_USER=self.username) |
| 638 |
self.assertEqual(response.status_code, status.HTTP_200_OK) |