2013-02-01 18:03:28 +04:00
|
|
|
from __future__ import unicode_literals
|
2013-09-25 13:30:04 +04:00
|
|
|
from django.conf.urls import patterns, url, include
|
2012-09-20 16:06:27 +04:00
|
|
|
from django.contrib.auth.models import User
|
2012-12-20 03:12:27 +04:00
|
|
|
from django.http import HttpResponse
|
2013-06-28 20:50:30 +04:00
|
|
|
from django.test import TestCase
|
2014-09-06 02:30:01 +04:00
|
|
|
from django.utils import six
|
2013-02-01 18:03:28 +04:00
|
|
|
from rest_framework import HTTP_HEADER_ENCODING
|
2013-02-28 21:58:58 +04:00
|
|
|
from rest_framework import exceptions
|
2012-09-20 16:06:27 +04:00
|
|
|
from rest_framework import permissions
|
2013-06-03 15:32:57 +04:00
|
|
|
from rest_framework import renderers
|
|
|
|
from rest_framework.response import Response
|
2013-02-25 17:59:40 +04:00
|
|
|
from rest_framework import status
|
2013-02-28 21:58:58 +04:00
|
|
|
from rest_framework.authentication import (
|
|
|
|
BaseAuthentication,
|
|
|
|
TokenAuthentication,
|
|
|
|
BasicAuthentication,
|
2013-03-07 13:01:53 +04:00
|
|
|
SessionAuthentication,
|
2013-02-28 21:58:58 +04:00
|
|
|
)
|
2012-09-20 16:06:27 +04:00
|
|
|
from rest_framework.authtoken.models import Token
|
2013-06-28 20:50:30 +04:00
|
|
|
from rest_framework.test import APIRequestFactory, APIClient
|
2012-12-20 03:12:27 +04:00
|
|
|
from rest_framework.views import APIView
|
2012-09-20 16:06:27 +04:00
|
|
|
import base64
|
|
|
|
|
2013-06-28 20:17:39 +04:00
|
|
|
factory = APIRequestFactory()
|
2013-02-28 21:58:58 +04:00
|
|
|
|
|
|
|
|
2012-09-20 16:06:27 +04:00
|
|
|
class MockView(APIView):
|
|
|
|
permission_classes = (permissions.IsAuthenticated,)
|
|
|
|
|
2013-02-28 21:58:58 +04:00
|
|
|
def get(self, request):
|
|
|
|
return HttpResponse({'a': 1, 'b': 2, 'c': 3})
|
|
|
|
|
2012-09-20 16:06:27 +04:00
|
|
|
def post(self, request):
|
|
|
|
return HttpResponse({'a': 1, 'b': 2, 'c': 3})
|
|
|
|
|
|
|
|
def put(self, request):
|
|
|
|
return HttpResponse({'a': 1, 'b': 2, 'c': 3})
|
|
|
|
|
2013-02-28 21:58:58 +04:00
|
|
|
|
2014-08-19 16:28:07 +04:00
|
|
|
urlpatterns = patterns(
|
|
|
|
'',
|
2013-01-22 01:29:49 +04:00
|
|
|
(r'^session/$', MockView.as_view(authentication_classes=[SessionAuthentication])),
|
|
|
|
(r'^basic/$', MockView.as_view(authentication_classes=[BasicAuthentication])),
|
|
|
|
(r'^token/$', MockView.as_view(authentication_classes=[TokenAuthentication])),
|
2012-12-08 02:25:16 +04:00
|
|
|
(r'^auth-token/$', 'rest_framework.authtoken.views.obtain_auth_token'),
|
2014-09-01 12:07:05 +04:00
|
|
|
url(r'^auth/', include('rest_framework.urls', namespace='rest_framework'))
|
2012-09-20 16:06:27 +04:00
|
|
|
)
|
|
|
|
|
2014-08-19 16:28:07 +04:00
|
|
|
|
2012-09-20 16:06:27 +04:00
|
|
|
class BasicAuthTests(TestCase):
|
|
|
|
"""Basic authentication"""
|
2014-03-02 15:40:30 +04:00
|
|
|
urls = 'tests.test_authentication'
|
2012-09-20 16:06:27 +04:00
|
|
|
|
|
|
|
def setUp(self):
|
2013-06-28 20:50:30 +04:00
|
|
|
self.csrf_client = APIClient(enforce_csrf_checks=True)
|
2012-09-20 16:06:27 +04:00
|
|
|
self.username = 'john'
|
|
|
|
self.email = 'lennon@thebeatles.com'
|
|
|
|
self.password = 'password'
|
|
|
|
self.user = User.objects.create_user(self.username, self.email, self.password)
|
|
|
|
|
|
|
|
def test_post_form_passing_basic_auth(self):
|
|
|
|
"""Ensure POSTing json over basic auth with correct credentials passes and does not require CSRF"""
|
2013-02-01 18:03:28 +04:00
|
|
|
credentials = ('%s:%s' % (self.username, self.password))
|
|
|
|
base64_credentials = base64.b64encode(credentials.encode(HTTP_HEADER_ENCODING)).decode(HTTP_HEADER_ENCODING)
|
|
|
|
auth = 'Basic %s' % base64_credentials
|
2013-01-22 01:29:49 +04:00
|
|
|
response = self.csrf_client.post('/basic/', {'example': 'example'}, HTTP_AUTHORIZATION=auth)
|
2013-02-25 17:59:40 +04:00
|
|
|
self.assertEqual(response.status_code, status.HTTP_200_OK)
|
2012-09-20 16:06:27 +04:00
|
|
|
|
|
|
|
def test_post_json_passing_basic_auth(self):
|
|
|
|
"""Ensure POSTing form over basic auth with correct credentials passes and does not require CSRF"""
|
2013-02-01 18:03:28 +04:00
|
|
|
credentials = ('%s:%s' % (self.username, self.password))
|
|
|
|
base64_credentials = base64.b64encode(credentials.encode(HTTP_HEADER_ENCODING)).decode(HTTP_HEADER_ENCODING)
|
|
|
|
auth = 'Basic %s' % base64_credentials
|
2013-06-28 20:50:30 +04:00
|
|
|
response = self.csrf_client.post('/basic/', {'example': 'example'}, format='json', HTTP_AUTHORIZATION=auth)
|
2013-02-25 17:59:40 +04:00
|
|
|
self.assertEqual(response.status_code, status.HTTP_200_OK)
|
2012-09-20 16:06:27 +04:00
|
|
|
|
|
|
|
def test_post_form_failing_basic_auth(self):
|
|
|
|
"""Ensure POSTing form over basic auth without correct credentials fails"""
|
2013-01-22 01:29:49 +04:00
|
|
|
response = self.csrf_client.post('/basic/', {'example': 'example'})
|
2013-02-25 17:59:40 +04:00
|
|
|
self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)
|
2012-09-20 16:06:27 +04:00
|
|
|
|
|
|
|
def test_post_json_failing_basic_auth(self):
|
|
|
|
"""Ensure POSTing json over basic auth without correct credentials fails"""
|
2013-06-28 20:50:30 +04:00
|
|
|
response = self.csrf_client.post('/basic/', {'example': 'example'}, format='json')
|
2013-02-25 17:59:40 +04:00
|
|
|
self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)
|
2013-01-22 01:29:49 +04:00
|
|
|
self.assertEqual(response['WWW-Authenticate'], 'Basic realm="api"')
|
2012-09-20 16:06:27 +04:00
|
|
|
|
|
|
|
|
|
|
|
class SessionAuthTests(TestCase):
|
|
|
|
"""User session authentication"""
|
2014-03-02 15:40:30 +04:00
|
|
|
urls = 'tests.test_authentication'
|
2012-09-20 16:06:27 +04:00
|
|
|
|
|
|
|
def setUp(self):
|
2013-06-28 20:50:30 +04:00
|
|
|
self.csrf_client = APIClient(enforce_csrf_checks=True)
|
|
|
|
self.non_csrf_client = APIClient(enforce_csrf_checks=False)
|
2012-09-20 16:06:27 +04:00
|
|
|
self.username = 'john'
|
|
|
|
self.email = 'lennon@thebeatles.com'
|
|
|
|
self.password = 'password'
|
|
|
|
self.user = User.objects.create_user(self.username, self.email, self.password)
|
|
|
|
|
|
|
|
def tearDown(self):
|
|
|
|
self.csrf_client.logout()
|
|
|
|
|
2014-09-01 12:07:05 +04:00
|
|
|
def test_login_view_renders_on_get(self):
|
|
|
|
"""
|
|
|
|
Ensure the login template renders for a basic GET.
|
|
|
|
|
|
|
|
cf. [#1810](https://github.com/tomchristie/django-rest-framework/pull/1810)
|
|
|
|
"""
|
|
|
|
response = self.csrf_client.get('/auth/login/')
|
2014-12-07 23:05:17 +03:00
|
|
|
self.assertContains(response, '<label for="id_username">Username:</label>')
|
2014-09-01 12:07:05 +04:00
|
|
|
|
2012-09-20 16:06:27 +04:00
|
|
|
def test_post_form_session_auth_failing_csrf(self):
|
|
|
|
"""
|
|
|
|
Ensure POSTing form over session authentication without CSRF token fails.
|
|
|
|
"""
|
|
|
|
self.csrf_client.login(username=self.username, password=self.password)
|
2013-01-22 01:29:49 +04:00
|
|
|
response = self.csrf_client.post('/session/', {'example': 'example'})
|
2013-02-25 17:59:40 +04:00
|
|
|
self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)
|
2012-09-20 16:06:27 +04:00
|
|
|
|
|
|
|
def test_post_form_session_auth_passing(self):
|
|
|
|
"""
|
|
|
|
Ensure POSTing form over session authentication with logged in user and CSRF token passes.
|
|
|
|
"""
|
|
|
|
self.non_csrf_client.login(username=self.username, password=self.password)
|
2013-01-22 01:29:49 +04:00
|
|
|
response = self.non_csrf_client.post('/session/', {'example': 'example'})
|
2013-02-25 17:59:40 +04:00
|
|
|
self.assertEqual(response.status_code, status.HTTP_200_OK)
|
2012-09-20 16:06:27 +04:00
|
|
|
|
|
|
|
def test_put_form_session_auth_passing(self):
|
|
|
|
"""
|
|
|
|
Ensure PUTting form over session authentication with logged in user and CSRF token passes.
|
|
|
|
"""
|
|
|
|
self.non_csrf_client.login(username=self.username, password=self.password)
|
2013-01-22 01:29:49 +04:00
|
|
|
response = self.non_csrf_client.put('/session/', {'example': 'example'})
|
2013-02-25 17:59:40 +04:00
|
|
|
self.assertEqual(response.status_code, status.HTTP_200_OK)
|
2012-09-20 16:06:27 +04:00
|
|
|
|
|
|
|
def test_post_form_session_auth_failing(self):
|
|
|
|
"""
|
|
|
|
Ensure POSTing form over session authentication without logged in user fails.
|
|
|
|
"""
|
2013-01-22 01:29:49 +04:00
|
|
|
response = self.csrf_client.post('/session/', {'example': 'example'})
|
2013-02-25 17:59:40 +04:00
|
|
|
self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)
|
2012-09-20 16:06:27 +04:00
|
|
|
|
|
|
|
|
|
|
|
class TokenAuthTests(TestCase):
|
|
|
|
"""Token authentication"""
|
2014-03-02 15:40:30 +04:00
|
|
|
urls = 'tests.test_authentication'
|
2012-09-20 16:06:27 +04:00
|
|
|
|
|
|
|
def setUp(self):
|
2013-06-28 20:50:30 +04:00
|
|
|
self.csrf_client = APIClient(enforce_csrf_checks=True)
|
2012-09-20 16:06:27 +04:00
|
|
|
self.username = 'john'
|
|
|
|
self.email = 'lennon@thebeatles.com'
|
|
|
|
self.password = 'password'
|
|
|
|
self.user = User.objects.create_user(self.username, self.email, self.password)
|
|
|
|
|
|
|
|
self.key = 'abcd1234'
|
|
|
|
self.token = Token.objects.create(key=self.key, user=self.user)
|
|
|
|
|
|
|
|
def test_post_form_passing_token_auth(self):
|
|
|
|
"""Ensure POSTing json over token auth with correct credentials passes and does not require CSRF"""
|
2013-03-09 02:56:24 +04:00
|
|
|
auth = 'Token ' + self.key
|
2013-01-22 01:29:49 +04:00
|
|
|
response = self.csrf_client.post('/token/', {'example': 'example'}, HTTP_AUTHORIZATION=auth)
|
2013-02-25 17:59:40 +04:00
|
|
|
self.assertEqual(response.status_code, status.HTTP_200_OK)
|
2012-09-20 16:06:27 +04:00
|
|
|
|
|
|
|
def test_post_json_passing_token_auth(self):
|
|
|
|
"""Ensure POSTing form over token auth with correct credentials passes and does not require CSRF"""
|
|
|
|
auth = "Token " + self.key
|
2013-06-28 20:50:30 +04:00
|
|
|
response = self.csrf_client.post('/token/', {'example': 'example'}, format='json', HTTP_AUTHORIZATION=auth)
|
2013-02-25 17:59:40 +04:00
|
|
|
self.assertEqual(response.status_code, status.HTTP_200_OK)
|
2012-09-20 16:06:27 +04:00
|
|
|
|
2015-02-04 17:08:41 +03:00
|
|
|
def test_post_json_makes_one_db_query(self):
|
|
|
|
"""Ensure that authenticating a user using a token performs only one DB query"""
|
|
|
|
auth = "Token " + self.key
|
2015-02-09 20:43:20 +03:00
|
|
|
|
|
|
|
def func_to_test():
|
|
|
|
return self.csrf_client.post('/token/', {'example': 'example'}, format='json', HTTP_AUTHORIZATION=auth)
|
|
|
|
|
2015-02-04 17:08:41 +03:00
|
|
|
self.assertNumQueries(1, func_to_test)
|
|
|
|
|
2012-09-20 16:06:27 +04:00
|
|
|
def test_post_form_failing_token_auth(self):
|
|
|
|
"""Ensure POSTing form over token auth without correct credentials fails"""
|
2013-01-22 01:29:49 +04:00
|
|
|
response = self.csrf_client.post('/token/', {'example': 'example'})
|
2013-02-25 17:59:40 +04:00
|
|
|
self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)
|
2012-09-20 16:06:27 +04:00
|
|
|
|
|
|
|
def test_post_json_failing_token_auth(self):
|
|
|
|
"""Ensure POSTing json over token auth without correct credentials fails"""
|
2013-06-28 20:50:30 +04:00
|
|
|
response = self.csrf_client.post('/token/', {'example': 'example'}, format='json')
|
2013-02-25 17:59:40 +04:00
|
|
|
self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)
|
2012-09-20 16:06:27 +04:00
|
|
|
|
|
|
|
def test_token_has_auto_assigned_key_if_none_provided(self):
|
|
|
|
"""Ensure creating a token with no key will auto-assign a key"""
|
2012-10-09 12:57:31 +04:00
|
|
|
self.token.delete()
|
2012-09-20 16:06:27 +04:00
|
|
|
token = Token.objects.create(user=self.user)
|
|
|
|
self.assertTrue(bool(token.key))
|
2012-11-11 04:17:50 +04:00
|
|
|
|
2014-04-28 15:35:55 +04:00
|
|
|
def test_generate_key_returns_string(self):
|
|
|
|
"""Ensure generate_key returns a string"""
|
|
|
|
token = Token()
|
|
|
|
key = token.generate_key()
|
2014-04-28 16:13:51 +04:00
|
|
|
self.assertTrue(isinstance(key, six.string_types))
|
2014-04-28 15:35:55 +04:00
|
|
|
|
2012-11-11 04:17:50 +04:00
|
|
|
def test_token_login_json(self):
|
|
|
|
"""Ensure token login view using JSON POST works."""
|
2013-06-28 20:50:30 +04:00
|
|
|
client = APIClient(enforce_csrf_checks=True)
|
2012-12-08 02:25:16 +04:00
|
|
|
response = client.post('/auth-token/',
|
2013-06-28 20:50:30 +04:00
|
|
|
{'username': self.username, 'password': self.password}, format='json')
|
2013-02-25 17:59:40 +04:00
|
|
|
self.assertEqual(response.status_code, status.HTTP_200_OK)
|
2013-06-28 20:50:30 +04:00
|
|
|
self.assertEqual(response.data['token'], self.key)
|
2012-11-11 04:17:50 +04:00
|
|
|
|
|
|
|
def test_token_login_json_bad_creds(self):
|
|
|
|
"""Ensure token login view using JSON POST fails if bad credentials are used."""
|
2013-06-28 20:50:30 +04:00
|
|
|
client = APIClient(enforce_csrf_checks=True)
|
2012-12-08 02:25:16 +04:00
|
|
|
response = client.post('/auth-token/',
|
2013-06-28 20:50:30 +04:00
|
|
|
{'username': self.username, 'password': "badpass"}, format='json')
|
2012-12-08 02:25:16 +04:00
|
|
|
self.assertEqual(response.status_code, 400)
|
2012-11-11 04:17:50 +04:00
|
|
|
|
|
|
|
def test_token_login_json_missing_fields(self):
|
|
|
|
"""Ensure token login view using JSON POST fails if missing fields."""
|
2013-06-28 20:50:30 +04:00
|
|
|
client = APIClient(enforce_csrf_checks=True)
|
2012-12-08 02:25:16 +04:00
|
|
|
response = client.post('/auth-token/',
|
2013-06-28 20:50:30 +04:00
|
|
|
{'username': self.username}, format='json')
|
2012-12-08 02:25:16 +04:00
|
|
|
self.assertEqual(response.status_code, 400)
|
2012-11-11 04:17:50 +04:00
|
|
|
|
|
|
|
def test_token_login_form(self):
|
|
|
|
"""Ensure token login view using form POST works."""
|
2013-06-28 20:50:30 +04:00
|
|
|
client = APIClient(enforce_csrf_checks=True)
|
2012-12-08 02:25:16 +04:00
|
|
|
response = client.post('/auth-token/',
|
2012-11-13 03:16:53 +04:00
|
|
|
{'username': self.username, 'password': self.password})
|
2013-02-25 17:59:40 +04:00
|
|
|
self.assertEqual(response.status_code, status.HTTP_200_OK)
|
2013-06-28 20:50:30 +04:00
|
|
|
self.assertEqual(response.data['token'], self.key)
|
2013-02-28 21:58:58 +04:00
|
|
|
|
|
|
|
|
|
|
|
class IncorrectCredentialsTests(TestCase):
|
|
|
|
def test_incorrect_credentials(self):
|
|
|
|
"""
|
|
|
|
If a request contains bad authentication credentials, then
|
|
|
|
authentication should run and error, even if no permissions
|
|
|
|
are set on the view.
|
|
|
|
"""
|
|
|
|
class IncorrectCredentialsAuth(BaseAuthentication):
|
|
|
|
def authenticate(self, request):
|
|
|
|
raise exceptions.AuthenticationFailed('Bad credentials')
|
|
|
|
|
|
|
|
request = factory.get('/')
|
|
|
|
view = MockView.as_view(
|
|
|
|
authentication_classes=(IncorrectCredentialsAuth,),
|
|
|
|
permission_classes=()
|
|
|
|
)
|
|
|
|
response = view(request)
|
|
|
|
self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)
|
|
|
|
self.assertEqual(response.data, {'detail': 'Bad credentials'})
|
2013-03-07 13:01:53 +04:00
|
|
|
|
|
|
|
|
2013-06-03 15:32:57 +04:00
|
|
|
class FailingAuthAccessedInRenderer(TestCase):
|
|
|
|
def setUp(self):
|
|
|
|
class AuthAccessingRenderer(renderers.BaseRenderer):
|
|
|
|
media_type = 'text/plain'
|
|
|
|
format = 'txt'
|
|
|
|
|
|
|
|
def render(self, data, media_type=None, renderer_context=None):
|
|
|
|
request = renderer_context['request']
|
|
|
|
if request.user.is_authenticated():
|
|
|
|
return b'authenticated'
|
|
|
|
return b'not authenticated'
|
|
|
|
|
|
|
|
class FailingAuth(BaseAuthentication):
|
|
|
|
def authenticate(self, request):
|
|
|
|
raise exceptions.AuthenticationFailed('authentication failed')
|
|
|
|
|
|
|
|
class ExampleView(APIView):
|
|
|
|
authentication_classes = (FailingAuth,)
|
|
|
|
renderer_classes = (AuthAccessingRenderer,)
|
|
|
|
|
|
|
|
def get(self, request):
|
|
|
|
return Response({'foo': 'bar'})
|
|
|
|
|
|
|
|
self.view = ExampleView.as_view()
|
|
|
|
|
|
|
|
def test_failing_auth_accessed_in_renderer(self):
|
|
|
|
"""
|
|
|
|
When authentication fails the renderer should still be able to access
|
|
|
|
`request.user` without raising an exception. Particularly relevant
|
|
|
|
to HTML responses that might reasonably access `request.user`.
|
|
|
|
"""
|
|
|
|
request = factory.get('/')
|
|
|
|
response = self.view(request)
|
|
|
|
content = response.render().content
|
|
|
|
self.assertEqual(content, b'not authenticated')
|