Open Source Platform for DTC, B2B Commerce, Marketplaces & Omnichannel. REST APIs, TypeScript SDKs, and production-ready Next.js storefront. Self-host it. Own your data. No vendor lock-in. Zero platform fees.
Ruby b2b-commercee-commerceecommerceecommerce-apiecommerce-frameworkecommerce-platformheadlessheadless-commerceheadless-ecommercemarketplacemulti-tenantmulti-vendormulti-vendor-ecommerceopen-sourcespree-commerce
Complete the SSO callback flow
Damian Legawiec9cbaf2082ddc
diff --git a/packages/dashboard/src/routes/login.tsx b/packages/dashboard/src/routes/login.tsxindex 967b6f3900..12345db26a 100644--- a/packages/dashboard/src/routes/login.tsx+++ b/packages/dashboard/src/routes/login.tsx@@ -201,6 +201,8 @@ function ProvidersUnavailable() {const CALLBACK_ERROR_KEYS: Record<string, string> = {account_not_provisioned: 'admin.auth.login.account_not_provisioned',invalid_oauth_state: 'admin.auth.login.invalid_oauth_state',+ invalid_provider: 'admin.auth.login.sso_failed',+ authentication_failed: 'admin.auth.login.sso_failed',}function CallbackError({ code }: { code: string }) {diff --git a/spree/api/app/controllers/spree/api/v3/admin/auth_controller.rb b/spree/api/app/controllers/spree/api/v3/admin/auth_controller.rbindex 0e7895fab3..eb1ab1a993 100644--- a/spree/api/app/controllers/spree/api/v3/admin/auth_controller.rb+++ b/spree/api/app/controllers/spree/api/v3/admin/auth_controller.rb@@ -49,29 +49,32 @@ module Spree# GET /api/v3/admin/auth/callback/:provider#- # Completes a redirect (SSO) login. Terminates in the same access JWT +- # refresh-token cookie the password flow issues — no separate session- # mechanism for SSO.+ # Completes a redirect (SSO) login.+ #+ # Reached by a full-page browser redirect from the identity provider, so+ # it answers with a redirect rather than JSON — the browser must land on+ # the dashboard, not on a response body. Success sets the same+ # refresh-token cookie the password flow issues and the SPA mints its+ # access token from it on load, so no token ever travels in a URL.def callback- return render_invalid_state unless valid_oauth_state?+ return redirect_to_dashboard(error: ERROR_CODES[:invalid_oauth_state]) unless valid_oauth_state?- strategy = authentication_strategy(params[:provider])- return unless strategy+ strategy = Spree.admin_authentication_strategies.build(+ params[:provider],+ params: params,+ request_env: request.headers.env,+ user_class: Spree.admin_user_class+ )+ return redirect_to_dashboard(error: ERROR_CODES[:invalid_provider]) if strategy.nil?result = strategy.callback- if result.success?- user = result.value- refresh_token = Spree::RefreshToken.create_for(user, request_env: request_env_for_token)- set_refresh_cookie(refresh_token)- render json: auth_response(user)- else- render_error(- code: ERROR_CODES[:account_not_provisioned],- message: result.error,- status: :unauthorized- )+ unless result.success?+ return redirect_to_dashboard(error: callback_error_code(strategy))end++ set_refresh_cookie(Spree::RefreshToken.create_for(result.value, request_env: request_env_for_token))+ redirect_to_dashboardend# POST /api/v3/admin/auth/refresh@@ -143,12 +146,34 @@ module Spreepayload['provider'].to_s == params[:provider].to_send- def render_invalid_state- render_error(- code: ERROR_CODES[:invalid_oauth_state],- message: Spree.t('errors.messages.invalid_oauth_state'),- status: :unauthorized- )+ # Sends the browser back to the dashboard. On failure the login page+ # reads +?error=+ and explains what happened; on success it has the+ # refresh cookie and completes sign-in through its normal boot refresh.+ def redirect_to_dashboard(error: nil)+ target = dashboard_url+ target = "#{target}/login?error=#{error}" if error.present?++ redirect_to target, allow_other_host: true+ end++ # Where the React dashboard is hosted. Falls back to the Vite dev server+ # in development, then to the store's own URL.+ def dashboard_url+ base = Spree::Config[:dashboard_url].presence ||+ (Rails.env.development? ? 'http://localhost:5173' : nil) ||+ current_store&.formatted_url++ base.to_s.chomp('/')+ end++ # A technical SSO failure (missing code, token verification) must not be+ # reported as "ask an administrator for an invitation".+ def callback_error_code(strategy)+ if strategy.respond_to?(:account_not_provisioned?) && strategy.account_not_provisioned?+ ERROR_CODES[:account_not_provisioned]+ else+ ERROR_CODES[:authentication_failed]+ endenddef authentication_strategiesdiff --git a/spree/api/spec/controllers/spree/api/v3/admin/auth_controller_spec.rb b/spree/api/spec/controllers/spree/api/v3/admin/auth_controller_spec.rbindex 12c5e74085..fd5ec62c0e 100644--- a/spree/api/spec/controllers/spree/api/v3/admin/auth_controller_spec.rb+++ b/spree/api/spec/controllers/spree/api/v3/admin/auth_controller_spec.rb@@ -405,18 +405,22 @@ RSpec.describe Spree::Api::V3::Admin::AuthController, type: :controller dostub_claims('sub' => 'idp-subject-1', 'email' => admin.email, 'email_verified' => 'true')end- it 'signs the admin in with the same token pair as password login' do+ # The browser arrives here from the identity provider, so the response has+ # to be a redirect — a JSON body would leave the admin staring at raw text.+ it 'redirects the browser to the dashboard without an error' doget :callback, params: { provider: 'entra', code: 'auth-code', state: valid_state }- expect(response).to have_http_status(:ok)- expect(json_response['token']).to be_present- expect(json_response['user']['email']).to eq(admin.email)+ expect(response).to have_http_status(:redirect)+ expect(response.location).not_to include('error=')end- it 'sets the refresh cookie' do+ # The SPA mints its access token from the cookie on load, so no token ever+ # travels in the redirect URL.+ it 'sets the refresh cookie and keeps tokens out of the URL' doget :callback, params: { provider: 'entra', code: 'auth-code', state: valid_state }expect(set_cookie_for('spree_admin_refresh_token')).to be_present+ expect(response.location).not_to include('token')endit 'links the SSO identity to the existing account' do@@ -434,7 +438,7 @@ RSpec.describe Spree::Api::V3::Admin::AuthController, type: :controller doit 'refuses to claim the account' doget :callback, params: { provider: 'entra', code: 'auth-code', state: valid_state }- expect(response).to have_http_status(:unauthorized)+ expect(response).to redirect_to(/error=account_not_provisioned/)expect(admin.identities).to be_emptyendend@@ -449,8 +453,30 @@ RSpec.describe Spree::Api::V3::Admin::AuthController, type: :controller doget :callback, params: { provider: 'entra', code: 'auth-code', state: valid_state }}.not_to change(Spree.admin_user_class, :count)- expect(response).to have_http_status(:unauthorized)- expect(json_response['error']['code']).to eq('account_not_provisioned')+ expect(response).to redirect_to(/error=account_not_provisioned/)+ end+ end++ # A technical failure must not tell the person to ask for an invitation —+ # that advice only fits an authenticated subject with no authorized account.+ context 'when the provider exchange fails' do+ before do+ allow_any_instance_of(Spree::Authentication::Strategies::OidcStrategy).+ to receive(:exchange_code_for_tokens).and_raise(StandardError, 'token endpoint returned 500')+ end++ it 'redirects with authentication_failed, not account_not_provisioned' do+ get :callback, params: { provider: 'entra', code: 'auth-code', state: valid_state }++ expect(response).to redirect_to(/error=authentication_failed/)+ end+ end++ context 'when the identity provider returns no authorization code' do+ it 'redirects with authentication_failed' do+ get :callback, params: { provider: 'entra', state: valid_state }++ expect(response).to redirect_to(/error=authentication_failed/)endend@@ -462,15 +488,13 @@ RSpec.describe Spree::Api::V3::Admin::AuthController, type: :controller doit 'rejects a forged state' doget :callback, params: { provider: 'entra', code: 'auth-code', state: 'forged' }- expect(response).to have_http_status(:unauthorized)- expect(json_response['error']['code']).to eq('invalid_oauth_state')+ expect(response).to redirect_to(/error=invalid_oauth_state/)endit 'rejects a missing state' doget :callback, params: { provider: 'entra', code: 'auth-code' }- expect(response).to have_http_status(:unauthorized)- expect(json_response['error']['code']).to eq('invalid_oauth_state')+ expect(response).to redirect_to(/error=invalid_oauth_state/)endit 'rejects an expired state' do@@ -478,16 +502,14 @@ RSpec.describe Spree::Api::V3::Admin::AuthController, type: :controller doget :callback, params: { provider: 'entra', code: 'auth-code', state: expired }- expect(response).to have_http_status(:unauthorized)- expect(json_response['error']['code']).to eq('invalid_oauth_state')+ expect(response).to redirect_to(/error=invalid_oauth_state/)end# A state minted for one provider must not authorize a different one.it 'rejects a state minted for another provider' doget :callback, params: { provider: 'entra', code: 'auth-code', state: state_for('other') }- expect(response).to have_http_status(:unauthorized)- expect(json_response['error']['code']).to eq('invalid_oauth_state')+ expect(response).to redirect_to(/error=invalid_oauth_state/)endend@@ -497,15 +519,13 @@ RSpec.describe Spree::Api::V3::Admin::AuthController, type: :controller doit 'rejects another provider\'s state before looking the provider up' doget :callback, params: { provider: 'nope', code: 'auth-code', state: valid_state }- expect(response).to have_http_status(:unauthorized)- expect(json_response['error']['code']).to eq('invalid_oauth_state')+ expect(response).to redirect_to(/error=invalid_oauth_state/)end- it 'returns invalid_provider once the state matches' do+ it 'redirects with invalid_provider once the state matches' doget :callback, params: { provider: 'nope', code: 'auth-code', state: state_for('nope') }- expect(response).to have_http_status(:bad_request)- expect(json_response['error']['code']).to eq('invalid_provider')+ expect(response).to redirect_to(/error=invalid_provider/)endendenddiff --git a/spree/core/app/models/spree/authentication/strategies/oidc_strategy.rb b/spree/core/app/models/spree/authentication/strategies/oidc_strategy.rbindex b92c1cb035..a921ec2bac 100644--- a/spree/core/app/models/spree/authentication/strategies/oidc_strategy.rb+++ b/spree/core/app/models/spree/authentication/strategies/oidc_strategy.rb@@ -129,13 +129,22 @@ module Spree# @return [Spree::ServiceModule::Result]def callbackcode = params[:code]- return failure(Spree.t('errors.messages.oidc_missing_code')) if code.blank?+ return authentication_failure(Spree.t('errors.messages.oidc_missing_code')) if code.blank?claims = verify_id_token(exchange_code_for_tokens(code).fetch('id_token'))resolve_user(claims)rescue StandardError => eRails.logger.error("[Spree] OIDC callback failed for #{config[:label] || config[:issuer]}: #{e.message}")- failure(Spree.t('errors.messages.oidc_authentication_failed'))+ authentication_failure(Spree.t('errors.messages.oidc_authentication_failed'))+ end++ # True when the last +#callback+ failed because no account here is+ # authorized for an otherwise-authenticated IdP subject, as opposed to a+ # technical failure (missing code, token verification). The two carry+ # different error codes and very different advice for the person.+ # @return [Boolean]+ def account_not_provisioned?+ @account_not_provisioned.present?endprivate@@ -150,7 +159,7 @@ module Spree# every member of a corporate tenant would become store staff.def resolve_user(claims)subject = claims['sub']- return failure(Spree.t('errors.messages.oidc_authentication_failed')) if subject.blank?+ return authentication_failure(Spree.t('errors.messages.oidc_authentication_failed')) if subject.blank?identity = Spree::UserIdentity.find_by(provider: registry_key,@@ -160,12 +169,22 @@ module Spreereturn success(identity.user) if identityuser = find_linkable_user(claims)- return failure(Spree.t('errors.messages.oidc_account_not_provisioned')) if user.nil?+ return not_provisioned_failure if user.nil?user.identities.create!(provider: registry_key, uid: subject, info: identity_info(claims))success(user)end+ def authentication_failure(message)+ @account_not_provisioned = false+ failure(message)+ end++ def not_provisioned_failure+ @account_not_provisioned = true+ failure(Spree.t('errors.messages.oidc_account_not_provisioned'))+ end+# Only an email the provider asserts as verified may claim an existing# account. Matching on an unverified claim would let anyone who can set# their IdP email to a staff address take that account over.@@ -175,7 +194,10 @@ module Spreeemail = claims['email']return nil if email.blank?- user_class.find_by(email: email.downcase)+ # Compared case-insensitively on both sides: the models normalize email+ # with +squish+ but never downcase, so a stored "[email protected]" would+ # not match a lowercased claim on a case-sensitive database.+ user_class.find_by(user_class.arel_table[:email].lower.eq(email.to_s.downcase))enddef identity_info(claims)diff --git a/spree/core/lib/spree/core/configuration.rb b/spree/core/lib/spree/core/configuration.rbindex 39957130b9..78b8e20591 100644--- a/spree/core/lib/spree/core/configuration.rb+++ b/spree/core/lib/spree/core/configuration.rb@@ -29,6 +29,10 @@ module Spree# Used by admin mailers; falls back to `http://localhost:5173` in dev# and the store's storefront URL otherwise. Set this in production.preference :admin_url, :string, default: nil+ # Origin where the React dashboard is hosted (e.g. `https://dashboard.shop.com`).+ # Where the SSO callback returns the browser after an identity provider+ # redirect. Distinct from `admin_url`, which points at the legacy admin.+ preference :dashboard_url, :string, default: nilpreference :allow_checkout_on_gateway_error, :boolean, default: falsepreference :allow_empty_price_amount, :boolean, default: falsepreference :allow_guest_checkout, :boolean, default: true, deprecated: true # this is only used in the rails frontend, and is not implemented in APIdiff --git a/spree/core/spec/models/spree/authentication/strategies/oidc_strategy_spec.rb b/spree/core/spec/models/spree/authentication/strategies/oidc_strategy_spec.rbindex a22e28c648..026d6b0f45 100644--- a/spree/core/spec/models/spree/authentication/strategies/oidc_strategy_spec.rb+++ b/spree/core/spec/models/spree/authentication/strategies/oidc_strategy_spec.rb@@ -97,6 +97,23 @@ describe Spree::Authentication::Strategies::OidcStrategy doexpect { second.callback }.not_to change(Spree::UserIdentity, :count)end+ # The models normalize email with squish but never downcase, so the match+ # has to be case-insensitive on both sides or linking silently fails on a+ # case-sensitive database.+ context 'when the stored email differs only by case' do+ let!(:admin) { create(:admin_user, email: '[email protected]') }+ let(:claims) do+ { 'sub' => 'idp-subject-1', 'email' => '[email protected]', 'email_verified' => 'true' }+ end++ it 'still links the identity to the existing admin' do+ result = strategy.callback++ expect(result).to be_success+ expect(result.value).to eq(admin)+ end+ end+context 'when the email is not verified by the provider' dolet(:claims) do{ 'sub' => 'idp-subject-1', 'email' => admin.email, 'email_verified' => 'false' }