From 8db4917f9a59ef9a2841c2d2a6432f618d65476c Mon Sep 17 00:00:00 2001 From: "T. Franzel" Date: Fri, 25 Oct 2024 22:52:20 +0200 Subject: [PATCH] fix unused OAuth2 scopes override #1319 --- .../contrib/django_oauth_toolkit.py | 7 +++- tests/contrib/test_oauth_toolkit.py | 40 +++++++++++++++++++ 2 files changed, 45 insertions(+), 2 deletions(-) diff --git a/drf_spectacular/contrib/django_oauth_toolkit.py b/drf_spectacular/contrib/django_oauth_toolkit.py index 9b0019bc..d60c509f 100644 --- a/drf_spectacular/contrib/django_oauth_toolkit.py +++ b/drf_spectacular/contrib/django_oauth_toolkit.py @@ -37,8 +37,11 @@ def get_security_definition(self, auto_schema): flows[flow_type]['tokenUrl'] = spectacular_settings.OAUTH2_TOKEN_URL if spectacular_settings.OAUTH2_REFRESH_URL: flows[flow_type]['refreshUrl'] = spectacular_settings.OAUTH2_REFRESH_URL - scope_backend = get_scopes_backend() - flows[flow_type]['scopes'] = scope_backend.get_all_scopes() + if spectacular_settings.OAUTH2_SCOPES: + flows[flow_type]['scopes'] = spectacular_settings.OAUTH2_SCOPES + else: + scope_backend = get_scopes_backend() + flows[flow_type]['scopes'] = scope_backend.get_all_scopes() return { 'type': 'oauth2', diff --git a/tests/contrib/test_oauth_toolkit.py b/tests/contrib/test_oauth_toolkit.py index 20fe5062..7fc79541 100644 --- a/tests/contrib/test_oauth_toolkit.py +++ b/tests/contrib/test_oauth_toolkit.py @@ -133,3 +133,43 @@ def test_oauth2_toolkit_scopes_backend(no_warnings): assert 'implicit' in oauth2['flows'] flow = oauth2['flows']['implicit'] assert 'test_backend_scope' in flow['scopes'] + + +@mock.patch( + 'drf_spectacular.settings.spectacular_settings.OAUTH2_SCOPES', + {"read": "Read scope", "burn": "Burn scope"}, +) +@mock.patch( + 'drf_spectacular.settings.spectacular_settings.OAUTH2_FLOWS', + ['implicit'] +) +@mock.patch( + 'drf_spectacular.settings.spectacular_settings.OAUTH2_REFRESH_URL', + 'http://127.0.0.1:8000/o/refresh' +) +@mock.patch( + 'drf_spectacular.settings.spectacular_settings.OAUTH2_AUTHORIZATION_URL', + 'http://127.0.0.1:8000/o/authorize' +) +@mock.patch( + 'oauth2_provider.settings.oauth2_settings.SCOPES', + {"read": "Reading scope", "write": "Writing scope", "extra_scope": "Extra Scope"}, +) +@mock.patch( + 'oauth2_provider.settings.oauth2_settings.DEFAULT_SCOPES', + ["read", "write"] +) +@pytest.mark.contrib('oauth2_provider') +def test_oauth2_toolkit_custom_scopes(no_warnings): + router = routers.SimpleRouter() + router.register('TokenHasReadWriteScope', TokenHasReadWriteScopeViewset, basename="x1") + + urlpatterns = [ + *router.urls, + path('o/', include('oauth2_provider.urls', namespace='oauth2_provider')), + ] + schema = generate_schema(None, patterns=urlpatterns) + + assert schema['components']['securitySchemes']['oauth2']['flows']['implicit']['scopes'] == { + 'burn': 'Burn scope', 'read': 'Read scope' + }