Skip to content

Saleor Core: the high performance, composable, headless commerce API.

fix: handle Google OAuth offline_access scope incompatibility in OIDC plugin (#18919)

Don Kendall0bce4b9b20a5
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 93cf9f3533..84d345f1ae 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -39,6 +39,7 @@ All notable, unreleased changes to this project will be documented in this file.
### Other changes
+- Fix Google OAuth OIDC login failing with `invalid_scope` error when `enable_refresh_token` is enabled. Google does not support the `offline_access` scope; use `access_type=offline` authorization parameter instead. - #18919 by @dnplkndll
- Fix send order confirmation email to staff - #18342 by @Shaokun-X
- Validation on `AppExtension` is now removed. Saleor will accept string values for `mount` and `target` from Manifest during App installation and JSON value for `options` field.
Validation is now performed on the frontend (Dashboard). This change increases velocity of features related to apps and extensions, now Dashboard is only entity that ensures the contract
diff --git a/saleor/plugins/openid_connect/plugin.py b/saleor/plugins/openid_connect/plugin.py
index 5b553c6caa..fe5c8f3e81 100644
--- a/saleor/plugins/openid_connect/plugin.py
+++ b/saleor/plugins/openid_connect/plugin.py
@@ -1,5 +1,6 @@
import logging
from typing import cast
+from urllib.parse import urlparse
from authlib.common.errors import AuthlibBaseError
from django.core import signing
@@ -218,6 +219,45 @@ class OpenIDConnectPlugin(BasePlugin):
}
)
+ def _is_google_provider(self) -> bool:
+ """Detect Google as the OIDC provider from configured URLs."""
+ urls_to_check = [
+ self.config.authorization_url or "",
+ self.config.json_web_key_set_url or "",
+ self.config.token_url or "",
+ ]
+ google_domains = {"accounts.google.com", "googleapis.com", "www.googleapis.com"}
+ return any(
+ urlparse(url).hostname in google_domains for url in urls_to_check if url
+ )
+
+ def _is_cognito_provider(self) -> bool:
+ """Detect AWS Cognito as the OIDC provider from the JWKS URL.
+
+ Cognito JWKS URLs follow the pattern:
+ https://cognito-idp.<Region>.amazonaws.com/<userPoolId>/.well-known/jwks.json
+ """
+ return bool(
+ self.config.json_web_key_set_url
+ and "cognito-idp." in self.config.json_web_key_set_url
+ )
+
+ def _should_include_offline_access_scope(self) -> bool:
+ if not self.config.enable_refresh_token:
+ return False
+ if not self.config.json_web_key_set_url:
+ return False
+ if self._is_cognito_provider():
+ # AWS Cognito does not support this scope, refresh tokens are issued
+ # out of the box.
+ return False
+ if self._is_google_provider():
+ # Google uses `access_type=offline` as an authorization parameter
+ # instead of the `offline_access` scope. The parameter is added in
+ # `external_authentication_url`.
+ return False
+ return True
+
def _get_oauth_session(self):
scope = "openid profile email"
if self.config.use_scope_permissions:
@@ -225,16 +265,7 @@ class OpenIDConnectPlugin(BasePlugin):
permissions.append(SALEOR_STAFF_PERMISSION)
scope_permissions = " ".join(permissions)
scope += f" {scope_permissions}"
- if self.config.enable_refresh_token and (
- self.config.json_web_key_set_url
- and "cognito-idp." not in self.config.json_web_key_set_url
- ):
- # AWS Cognito does not support this scope, refresh tokens are issued out of
- # the box.
- # Cognito detection method is rather crude, according to the documentation
- # JWKS (which is required for the correct configuration of the plugin) is placed under following address:
- # https://cognito-idp.<Region>.amazonaws.com/<userPoolId>/.well-known/jwks.json.
-
+ if self._should_include_offline_access_scope():
scope += " offline_access"
return OAuth2Client(
client_id=self.config.client_id,
@@ -374,6 +405,11 @@ class OpenIDConnectPlugin(BasePlugin):
}
if self.config.audience:
kwargs["audience"] = self.config.audience
+ if self.config.enable_refresh_token and self._is_google_provider():
+ # Google does not support the standard `offline_access` scope.
+ # Instead, it requires `access_type=offline` as a query parameter
+ # on the authorization URL to issue refresh tokens.
+ kwargs["access_type"] = "offline"
uri, state = self.oauth.create_authorization_url(
self.config.authorization_url, **kwargs
)
diff --git a/saleor/plugins/openid_connect/tests/test_plugin.py b/saleor/plugins/openid_connect/tests/test_plugin.py
index c4957f8cc9..db30ff982c 100644
--- a/saleor/plugins/openid_connect/tests/test_plugin.py
+++ b/saleor/plugins/openid_connect/tests/test_plugin.py
@@ -54,6 +54,76 @@ def test_get_oauth_session_dont_add_refresh_scope_when_enabled_and_configured_wi
assert "offline_access" not in session.scope
+def test_get_oauth_session_dont_add_refresh_scope_when_enabled_and_configured_with_google(
+ openid_plugin,
+):
+ """Google does not support `offline_access` scope; it uses `access_type=offline`."""
+ plugin = openid_plugin(
+ enable_refresh_token=True,
+ oauth_authorization_url="https://accounts.google.com/o/oauth2/v2/auth",
+ oauth_token_url="https://oauth2.googleapis.com/token",
+ json_web_key_set_url="https://www.googleapis.com/oauth2/v3/certs",
+ )
+ session = plugin._get_oauth_session()
+ assert "offline_access" not in session.scope
+
+
+def test_google_auth_url_includes_access_type_offline(openid_plugin, settings, rf):
+ """Verify Google auth URL includes `access_type=offline` when refresh tokens are enabled."""
+ settings.ALLOWED_CLIENT_HOSTS = ["*"]
+ plugin = openid_plugin(
+ enable_refresh_token=True,
+ oauth_authorization_url="https://accounts.google.com/o/oauth2/v2/auth",
+ oauth_token_url="https://oauth2.googleapis.com/token",
+ json_web_key_set_url="https://www.googleapis.com/oauth2/v3/certs",
+ client_id="test_client",
+ )
+ redirect_uri = "http://localhost:3000/oauth-callback/"
+ input = {"redirectUri": redirect_uri}
+ response = plugin.external_authentication_url(input, rf.request(), None)
+ auth_url = response.get("authorizationUrl")
+ parsed_qs = parse_qs(urlparse(auth_url).query)
+ assert parsed_qs["access_type"][0] == "offline"
+ assert "offline_access" not in plugin._get_oauth_session().scope
+
+
+def test_google_auth_url_without_refresh_token_does_not_include_access_type(
+ openid_plugin, settings, rf
+):
+ """Verify Google auth URL omits `access_type=offline` when refresh tokens are disabled."""
+ settings.ALLOWED_CLIENT_HOSTS = ["*"]
+ plugin = openid_plugin(
+ enable_refresh_token=False,
+ oauth_authorization_url="https://accounts.google.com/o/oauth2/v2/auth",
+ oauth_token_url="https://oauth2.googleapis.com/token",
+ json_web_key_set_url="https://www.googleapis.com/oauth2/v3/certs",
+ client_id="test_client",
+ )
+ redirect_uri = "http://localhost:3000/oauth-callback/"
+ input = {"redirectUri": redirect_uri}
+ response = plugin.external_authentication_url(input, rf.request(), None)
+ auth_url = response.get("authorizationUrl")
+ parsed_qs = parse_qs(urlparse(auth_url).query)
+ assert "access_type" not in parsed_qs
+ assert "offline_access" not in plugin._get_oauth_session().scope
+
+
+def test_non_google_auth_url_does_not_include_access_type(openid_plugin, settings, rf):
+ """Non-Google providers should not get `access_type=offline` in the auth URL."""
+ settings.ALLOWED_CLIENT_HOSTS = ["*"]
+ plugin = openid_plugin(
+ enable_refresh_token=True,
+ client_id="test_client",
+ )
+ redirect_uri = "http://localhost:3000/oauth-callback/"
+ input = {"redirectUri": redirect_uri}
+ response = plugin.external_authentication_url(input, rf.request(), None)
+ auth_url = response.get("authorizationUrl")
+ parsed_qs = parse_qs(urlparse(auth_url).query)
+ assert "access_type" not in parsed_qs
+ assert "offline_access" in plugin._get_oauth_session().scope
+
+
def test_external_authentication_url_returns_redirect_url(openid_plugin, settings, rf):
settings.ALLOWED_CLIENT_HOSTS = ["*"]
authorize_path = "/authorize"