File: test_client_authentication.py

package info (click to toggle)
python-oauthlib 3.1.0-2
  • links: PTS, VCS
  • area: main
  • in suites: bullseye, sid
  • size: 1,612 kB
  • sloc: python: 10,020; makefile: 4; sh: 3
file content (163 lines) | stat: -rw-r--r-- 6,924 bytes parent folder | download
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
"""Client authentication tests across all endpoints.

Client authentication in OAuth2 serve two purposes, to authenticate
confidential clients and to ensure public clients are in fact public. The
latter is achieved with authenticate_client_id and the former with
authenticate_client.

We make sure authentication is done by requiring a client object to be set
on the request object with a client_id parameter. The client_id attribute
prevents this check from being circumvented with a client form parameter.
"""
from __future__ import absolute_import, unicode_literals

import json

from unittest import mock

from oauthlib.oauth2 import (BackendApplicationServer, LegacyApplicationServer,
                             MobileApplicationServer, RequestValidator,
                             WebApplicationServer)

from ....unittest import TestCase
from .test_utils import get_fragment_credentials


class ClientAuthenticationTest(TestCase):

    def inspect_client(self, request, refresh_token=False):
        if not request.client or not request.client.client_id:
            raise ValueError()
        return 'abc'

    def setUp(self):
        self.validator = mock.MagicMock(spec=RequestValidator)
        self.validator.is_pkce_required.return_value = False
        self.validator.get_code_challenge.return_value = None
        self.validator.get_default_redirect_uri.return_value = 'http://i.b./path'
        self.web = WebApplicationServer(self.validator,
                token_generator=self.inspect_client)
        self.mobile = MobileApplicationServer(self.validator,
                token_generator=self.inspect_client)
        self.legacy = LegacyApplicationServer(self.validator,
                token_generator=self.inspect_client)
        self.backend = BackendApplicationServer(self.validator,
                token_generator=self.inspect_client)
        self.token_uri = 'http://example.com/path'
        self.auth_uri = 'http://example.com/path?client_id=abc&response_type=token'
        # should be base64 but no added value in this unittest
        self.basicauth_client_creds = {"Authorization": "john:doe"}
        self.basicauth_client_id = {"Authorization": "john:"}

    def set_client(self, request):
        request.client = mock.MagicMock()
        request.client.client_id = 'mocked'
        return True

    def set_client_id(self, client_id, request):
        request.client = mock.MagicMock()
        request.client.client_id = 'mocked'
        return True

    def basicauth_authenticate_client(self, request):
        assert "Authorization" in request.headers
        assert "john:doe" in request.headers["Authorization"]
        request.client = mock.MagicMock()
        request.client.client_id = 'mocked'
        return True

    def test_client_id_authentication(self):
        token_uri = 'http://example.com/path'

        # authorization code grant
        self.validator.authenticate_client.return_value = False
        self.validator.authenticate_client_id.return_value = False
        _, body, _ = self.web.create_token_response(token_uri,
                body='grant_type=authorization_code&code=mock')
        self.assertEqual(json.loads(body)['error'], 'invalid_client')

        self.validator.authenticate_client_id.return_value = True
        self.validator.authenticate_client.side_effect = self.set_client
        _, body, _ = self.web.create_token_response(token_uri,
                body='grant_type=authorization_code&code=mock')
        self.assertIn('access_token', json.loads(body))

        # implicit grant
        auth_uri = 'http://example.com/path?client_id=abc&response_type=token'
        self.assertRaises(ValueError, self.mobile.create_authorization_response,
                auth_uri, scopes=['random'])

        self.validator.validate_client_id.side_effect = self.set_client_id
        h, _, s = self.mobile.create_authorization_response(auth_uri, scopes=['random'])
        self.assertEqual(302, s)
        self.assertIn('Location', h)
        self.assertIn('access_token', get_fragment_credentials(h['Location']))

    def test_basicauth_web(self):
        self.validator.authenticate_client.side_effect = self.basicauth_authenticate_client
        _, body, _ = self.web.create_token_response(
            self.token_uri,
            body='grant_type=authorization_code&code=mock',
            headers=self.basicauth_client_creds
        )
        self.assertIn('access_token', json.loads(body))

    def test_basicauth_legacy(self):
        self.validator.authenticate_client.side_effect = self.basicauth_authenticate_client
        _, body, _ = self.legacy.create_token_response(
            self.token_uri,
            body='grant_type=password&username=abc&password=secret',
            headers=self.basicauth_client_creds
        )
        self.assertIn('access_token', json.loads(body))

    def test_basicauth_backend(self):
        self.validator.authenticate_client.side_effect = self.basicauth_authenticate_client
        _, body, _ = self.backend.create_token_response(
            self.token_uri,
            body='grant_type=client_credentials',
            headers=self.basicauth_client_creds
        )
        self.assertIn('access_token', json.loads(body))

    def test_basicauth_revoke(self):
        self.validator.authenticate_client.side_effect = self.basicauth_authenticate_client

        # legacy or any other uses the same RevocationEndpoint
        _, body, status = self.legacy.create_revocation_response(
            self.token_uri,
            body='token=foobar',
            headers=self.basicauth_client_creds
        )
        self.assertEqual(status, 200, body)

    def test_basicauth_introspect(self):
        self.validator.authenticate_client.side_effect = self.basicauth_authenticate_client

        # legacy or any other uses the same IntrospectEndpoint
        _, body, status = self.legacy.create_introspect_response(
            self.token_uri,
            body='token=foobar',
            headers=self.basicauth_client_creds
        )
        self.assertEqual(status, 200, body)

    def test_custom_authentication(self):
        token_uri = 'http://example.com/path'

        # authorization code grant
        self.assertRaises(NotImplementedError,
                self.web.create_token_response, token_uri,
                body='grant_type=authorization_code&code=mock')

        # password grant
        self.validator.authenticate_client.return_value = True
        self.assertRaises(NotImplementedError,
                self.legacy.create_token_response, token_uri,
                body='grant_type=password&username=abc&password=secret')

        # client credentials grant
        self.validator.authenticate_client.return_value = True
        self.assertRaises(NotImplementedError,
                self.backend.create_token_response, token_uri,
                body='grant_type=client_credentials')