|
10 | 10 | from rest_framework.exceptions import AuthenticationFailed |
11 | 11 | from rest_framework.test import APIRequestFactory |
12 | 12 |
|
13 | | -from credentials.apps.api.authentication import JwtAuthentication, pipeline_set_user_roles |
| 13 | +from credentials.apps.api.authentication import ( |
| 14 | + BearerAuthentication, JwtAuthentication, pipeline_set_user_roles |
| 15 | +) |
14 | 16 | from credentials.apps.api.jwt_decode_handler import api_settings as drf_jwt_settings |
15 | 17 | from credentials.apps.api.tests.mixins import JwtMixin |
16 | 18 | from credentials.apps.core.constants import Role |
@@ -146,3 +148,33 @@ def test_no_user(self): |
146 | 148 | """ |
147 | 149 | result = pipeline_set_user_roles({}, None) |
148 | 150 | self.assertEqual(result, {}) |
| 151 | + |
| 152 | + |
| 153 | +class BearerAuthenticationTests(TestCase): |
| 154 | + """ Tests for the BearerAuthentication class. """ |
| 155 | + |
| 156 | + def setUp(self): |
| 157 | + super(BearerAuthenticationTests, self).setUp() |
| 158 | + self.auth = BearerAuthentication() |
| 159 | + self.factory = APIRequestFactory() |
| 160 | + |
| 161 | + def _create_request(self, token='12345', token_name='Bearer'): |
| 162 | + """Create request with authorization header. """ |
| 163 | + auth_header = '{} {}'.format(token_name, token) |
| 164 | + request = self.factory.get('/', HTTP_AUTHORIZATION=auth_header) |
| 165 | + return request |
| 166 | + |
| 167 | + def test_authenticate_header(self): |
| 168 | + """The method should return the string Bearer.""" |
| 169 | + self.assertEqual(self.auth.authenticate_header(self._create_request()), 'Bearer') |
| 170 | + |
| 171 | + def test_authenticate_invalid_token(self): |
| 172 | + """If no token is supplied, or if the token contains spaces, the method should raise an exception.""" |
| 173 | + |
| 174 | + # Missing token |
| 175 | + request = self._create_request('') |
| 176 | + self.assertRaises(AuthenticationFailed, self.auth.authenticate, request) |
| 177 | + |
| 178 | + # Token with spaces |
| 179 | + request = self._create_request('abc 123 456') |
| 180 | + self.assertRaises(AuthenticationFailed, self.auth.authenticate, request) |
0 commit comments