Skip to content

armgit / spree

Public Imported from GitHub
0

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.

Add SSO sign-in to the admin dashboard

Damian Legawiec8dd89a6630ad
diff --git a/docs/plans/6.0-platform-auth.md b/docs/plans/6.0-platform-auth.md
index bba787389a..99173ea2b3 100644
--- a/docs/plans/6.0-platform-auth.md
+++ b/docs/plans/6.0-platform-auth.md
@@ -1,10 +1,10 @@
# Platform-Owned Authentication & User Model Rename
-**Status:** In Progress (RefreshToken shipped in 5.4 ✓; Phases 1–3 implemented — gem-owned `Spree::Customer`/`Spree::AdminUser` models + `Spree.customer_class` rename + `user_id`→`customer_id` (fresh-install migration ordering corrected — two redundant `spree_admin_users` ALTER migrations dropped); Phase 2 data migration implemented — `spree:upgrade:migrate_users_to_customers` (Path A) + custom-model recipe (Path B); Phase 4 mostly shipped earlier (refresh tokens + endpoints + rate limiting), with account-lockout **enforcement** + config prefs + admin-logout throttle landed; Phase 5 (Devise + legacy models removed, core/api-scoped; headless gem-owned `template.rb`) + Phase 6 (aliases kept, Devise docs swept) done; `spree/admin` removal, starter 5b, the 6.0 upgrade guide, and `spree_users` teardown deferred)
+**Status:** In Progress (RefreshToken shipped in 5.4 ✓; Phases 1–3 implemented — gem-owned `Spree::Customer`/`Spree::AdminUser` models + `Spree.customer_class` rename + `user_id`→`customer_id` (fresh-install migration ordering corrected — two redundant `spree_admin_users` ALTER migrations dropped); Phase 2 data migration implemented — `spree:upgrade:migrate_users_to_customers` (Path A) + custom-model recipe (Path B); Phase 4 mostly shipped earlier (refresh tokens + endpoints + rate limiting), with account-lockout **enforcement** + config prefs + admin-logout throttle landed; Phase 5 (Devise + legacy models removed, core/api-scoped; headless gem-owned `template.rb`) + Phase 6 (aliases kept, Devise docs swept) done; `spree/admin` removal, starter 5b, the 6.0 upgrade guide, and `spree_users` teardown deferred. **Two 6.0 items still open (2026-08-03):** password-length policy — there is currently no minimum at all (Phase 4) — and Phase 7, SSO/OIDC login in the React dashboard)
**Target:** Spree 5.4 (RefreshToken ✓) + Spree 6.0 (Devise removal, User→Customer rename)
**Depends on:** Admin SPA (6.0-admin-spa.md — removes Rails admin, kills Devise dependency) for Devise removal
**Author:** Damian + Claude
-**Last updated:** 2026-07-30
+**Last updated:** 2026-08-03
## Summary
@@ -75,6 +75,10 @@ Two changes in one plan:
- **Default models ship in the gem — the host app owns no auth code (2026-07-28).** `Spree::Customer` and `Spree::AdminUser` live in `spree_core` like any other Spree model (`Product`, `Order`). The only historic reason for a host-app-owned user model was Devise — `devise_for` routes and the `devise :...` declaration require an app-local class; dropping Devise removes that constraint. Gem-owned models mean every auth improvement (lockout tuning, rate limiting, MFA/passkeys, token hardening) arrives via a normal gem upgrade + migration instead of a changelog entry asking users to hand-edit scaffolded code. This matches the broader 6.0 strategy: customization via configuration and existing extension systems, not Rails code in the host app. Apps needing extra customer columns add their own migrations against `spree_customers` or use metafields.
- **No authentication generators at all.** Remove both `spree/authentication/devise/` and `spree/authentication/custom/` generator directories. The `inject_into_file` scaffolding is fragile (silently degrades to "add these lines manually" when the class definition doesn't match its anchor) and produces code frozen at generation time. Custom user classes remain fully supported — `Spree.customer_class = 'MyApp::User'` + one concern include — as a **documented recipe**, not generated code.
- **Keep the adapter pattern.** `Spree.store_authentication_strategies` lets developers plug in Auth0, Clerk, Firebase, LDAP, etc. by implementing `BaseStrategy`.
+- **The credential stays on the user model — no separate credential table (2026-08-03).** `password_digest` lives on `spree_customers` / `spree_admin_users`, not on `Spree::UserIdentity`. Surveyed platforms are split: Vendure keeps `passwordHash` on a `NativeAuthenticationMethod` row (STI alongside `ExternalAuthenticationMethod`), Medusa v2 keeps it in `provider_identity.provider_metadata`, and Saleor keeps it on the `User` row (inherited from Django's `AbstractBaseUser`). Vendure and Medusa gain two things from the split: several credentials of the same kind per user, and a clean "this account has no password" state. Spree already has the second — `password_digest` is nullable, `has_secure_password validations: false`, and `valid_password?` returns false on a blank digest, so a pure-SSO account is simply a row with no digest. (Saleor needs an "unusable password" sentinel only because Django's column is *not* nullable.) The first has no demand in commerce. Against that, moving the digest off the model would break `Spree.customer_class` pluggability: the Path B recipe below aliases `password_digest` to an app's legacy column *on the app's own model*, which only works while the credential belongs to the model. A separate table would force every custom user class to adopt Spree's identity table too — the opposite of "database tables stay configurable".
+- **SSO-only shops remove the `:email` strategy — there is no separate toggle (2026-08-03).** `Spree.admin_authentication_strategies.remove(:email)` makes password login structurally unreachable: the auth controllers resolve every login through the registry and return `invalid_provider` (400) for an unregistered key. No boolean preference — a second source of truth could disagree with the registry.
+- **Password policy is a plain Rails validator (2026-08-03).** Length bounds stay preferences — `Spree::Config[:minimum_password_length]` (default 8 — NIST 800-63B, no composition rules; matches Saleor) and `[:maximum_password_length]` (the bcrypt 72-byte cap) — because they are *values*. The policy itself is a **class**, so it follows the `Spree.<name>` accessor convention used by `customer_class`/`base_class`/`tax_provider`, **not** a `Spree::Config` string preference: `Spree.password_validator`, defaulting to `Spree::PasswordLengthValidator`, registered in `engine.rb` like `tax_provider`. Assigning a different `ActiveModel::Validator` replaces the policy wholesale. Not `Spree::Dependencies` either — that registry is for services and workflows you *call*, whereas this is a class-level policy like the other `Spree.` accessors. Vendure needs a bespoke `PasswordValidationStrategy` because TypeScript has no `validates_with`; Rails already has the extension point, and errors on `:password` reach the dashboard form through the existing 422 → `mapSpreeErrorsToForm` path, so a custom validator's message *is* the user-facing reason with no new plumbing.
+- **The dashboard login page is driven by the strategy registry, not hardcoded (2026-08-03).** See Phase 7.
### User → Customer/AdminUser rename
@@ -413,6 +417,33 @@ Landed:
Not pursued: hashing refresh tokens at rest (they're already random + expiring, and login is
rate-limited).
+**Open gap — no minimum password length.** Today `Spree::Customer` and `Spree::AdminUser` validate
+only `confirmation` and the bcrypt 72-byte cap, so a one-character admin password is valid. Of the
+platforms surveyed, Medusa ships no policy at all (a bare presence check, and no hook to add one),
+Vendure defaults to a deliberately permissive 4 behind a replaceable strategy, and Saleor enforces 8
+via a single Django `MinimumLengthValidator`. Close this before 6.0 ships:
+
+```ruby
+# spree/core/lib/spree/core/configuration.rb — values are preferences
+preference :minimum_password_length, :integer, default: 8
+preference :maximum_password_length, :integer, default: ActiveModel::SecurePassword::MAX_PASSWORD_LENGTH_ALLOWED
+
+# spree/core/lib/spree/core/engine.rb — the policy is a class, like tax_provider
+Rails.application.config.spree.password_validator = Spree::PasswordLengthValidator
+
+# Host app replaces the policy wholesale:
+Spree.password_validator = MyApp::PasswordValidator
+```
+
+Applies to both models via the shared `Spree::PasswordPolicy` concern, which is a thin
+`validate` hook delegating to `Spree.password_validator`. The maximum is a correctness guard rather
+than policy — bcrypt truncates past 72 bytes, so without it a long passphrase and its 72-byte prefix
+are the same password.
+
+Raising the floor on an existing install invalidates no stored digest — the validation runs on
+`password`, which is only present when a password is being set — so upgrades are safe and existing
+short passwords keep working until their next change.
+
### Phase 5: Remove Devise + all authentication generators — core/api done
Landed (scoped to `spree/core` + `spree/api`):
@@ -439,12 +470,107 @@ The starter currently ships the host-app auth code the generator produced. At 6.
### Phase 6: Cleanup (still 6.0) — partially done
-- **Deprecation aliases kept through 6.0** (revised): `Spree.user_class`/`user_class=`, `Spree::UserMethods`, `Spree::DeprecatedCustomerAlias`, and the `:user` factory alias all remain for 6.0. This supersedes the earlier "remove the `user_class` alias in 6.0" plan; their removal is extracted to Phase 7 (6.1).
+- **Deprecation aliases kept through 6.0** (revised): `Spree.user_class`/`user_class=`, `Spree::UserMethods`, `Spree::DeprecatedCustomerAlias`, and the `:user` factory alias all remain for 6.0. This supersedes the earlier "remove the `user_class` alias in 6.0" plan; their removal is extracted to Phase 8 (6.1).
- `Spree::OauthAccessToken`: nothing remains (extracted upstream to `legacy_api_v2`). No-op. ✓
- **Devise / `user_class` docs sweep — done**: rewrote the Devise-as-default pages (customization/authentication, admin/authentication, adding_spree_to_rails_app, customization/quickstart, admin.mdx) around the gem-owned `Spree::Customer`/`AdminUser` + `has_secure_password` + custom-model recipe, and swept `Spree.user_class` → `Spree.customer_class` across the incidental docs (kept the alias notes + historical upgrade guides). The multi-tenant quickstart's Devise example was left intact (it targets a Devise-based custom model) with a clarifying note.
- Deferred: the net-new `docs/developer/upgrades/5.6-to-6.0.mdx` (with the Path A/B migrate-users section), the `spree_users` table teardown task, and the search-area `multi_search` alias removal.
-### Phase 7: Remove deprecation aliases (6.1)
+### Phase 7: SSO / OIDC login in the React dashboard (6.0) — not started
+
+The registry supports SSO-only admins today, but the dashboard cannot see it. `packages/dashboard/src/routes/login.tsx` hardcodes the email/password form, so a shop that runs
+`Spree.admin_authentication_strategies.remove(:email)` still gets a password form that can only ever
+return `invalid_provider`. There is also no redirect-based login path at all: `BaseStrategy` assumes
+the client posts credentials to `auth/login`, which fits Auth0-style token verification but not the
+browser redirect that Microsoft Entra ID, Okta and Google Workspace actually use. Both halves are
+needed for the enterprise SSO story.
+
+**Strategy self-description (`spree/core`).** `BaseStrategy` grows a small class-level surface so the
+registry can describe itself, with defaults that keep existing custom strategies working unchanged:
+
+- `kind` — `:password` (client posts credentials) or `:redirect` (client sends the browser to the IdP). Defaults to `:password`.
+- `label` — human-readable provider name for the button (`"Microsoft Entra ID"`).
+- `authorization_url(state:)` — redirect providers only; where to send the browser.
+
+**Registry accepts configured factories (`spree/core`).** Both auth controllers currently do
+`strategy_class.new(params:, request_env:, user_class:)`, so the registry can only hold bare classes —
+which cannot carry per-registration config (issuer, client id/secret, label), and cannot express the
+same class registered twice under different keys. `StrategyRegistry` entries become "a class **or** an
+object responding to `#build(params:, request_env:, user_class:)`", and the controllers branch on
+`respond_to?(:build)`. Existing class registrations are untouched:
+
+```ruby
+Spree.admin_authentication_strategies.add(
+ :entra,
+ Spree::Authentication::Strategies::OidcStrategy.configure(
+ issuer: 'https://login.microsoftonline.com/<tenant>/v2.0',
+ client_id: ENV['ENTRA_CLIENT_ID'],
+ client_secret: ENV['ENTRA_CLIENT_SECRET'],
+ label: 'Microsoft Entra ID'
+ )
+)
+```
+
+**Reference provider: one generic OIDC strategy (2026-08-03).** `Spree::Authentication::Strategies::OidcStrategy`,
+configured by issuer discovery (`.well-known/openid-configuration`) plus client credentials, covers
+Entra ID, Okta, Google Workspace, Keycloak and Auth0 with no per-vendor code — the same choice
+commercetools made for enterprise SSO, which ships OIDC only and documents per-vendor *setup guides*
+rather than per-vendor classes. No named `EntraStrategy`; vendor specificity lives in docs and in the
+`issuer` value.
+
+**Discovery endpoint (`spree/api`) — Admin API only in 6.0.** `GET /api/v3/admin/auth/providers`,
+unauthenticated because it is consumed before login, returning the registered strategies. No store
+twin: the dashboard is the login UI Spree ships and controls, whereas headless storefronts own theirs
+and already know which strategies they registered. Revisit if storefront authors ask for it.
+
+```json
+{ "providers": [
+ { "key": "email", "kind": "password" },
+ { "key": "entra", "kind": "redirect", "label": "Microsoft Entra ID",
+ "authorization_url": "https://login.microsoftonline.com/…" }
+] }
+```
+
+Two constraints, both non-negotiable: it exposes **only** provider keys, kinds, labels and
+authorization URLs — never client secrets, never strategy class names — and it sits behind the
+existing auth rate limiter, since an open endpoint listing a shop's IdP is a fingerprinting surface.
+
+**OAuth callback (`spree/api`).** A new `GET /api/v3/admin/auth/callback/:provider` completes the
+redirect flow: it verifies the `state` parameter (CSRF), hands the authorization code to the
+strategy, resolves the user through `Spree::UserIdentity`, then issues the same access JWT +
+refresh-token cookie pair the password path already issues. **No new session mechanism** — the
+redirect flow terminates in exactly the tokens Phase 4 defined. Admin identities resolve with
+`user_class: Spree.admin_user_class`, so an SSO admin and an SSO customer with the same email stay
+distinct records.
+
+**Account resolution — three rules, settled 2026-08-03.** The callback resolves an IdP subject to an
+`AdminUser` in this order:
+
+1. **Known identity** — a `Spree::UserIdentity` matching `(provider, uid, user_type)` already exists. Log in.
+2. **Existing admin, first SSO login** — no identity yet, but an `AdminUser` has the same email **and the IdP asserts `email_verified: true`**. Link a new `UserIdentity` to that account and log in. This is what makes the migration path work: a shop registers Entra and its existing staff simply sign in, with no password round-trip — which matters most for the shop that also removed `:email`. The verified-claim requirement is not optional; matching on an unverified email claim lets anyone who can set their IdP email to a staff address take over that account.
+3. **Unknown subject** — no identity, no email match. **Rejected.** Admin accounts never auto-provision, or every member of a corporate Entra tenant becomes store staff. The person must be invited through the existing invitation flow first. Integrators may opt into JIT provisioning per strategy.
+
+Rule 3 rejects a person who authenticated successfully with their IdP, so a generic "authentication
+failed" reads as a broken login. The callback redirects to the dashboard login page with a distinct
+error code, and the page explains that the account is not authorised for this store and an
+administrator must send an invitation. Customers keep today's behaviour — `UserIdentity.find_or_create_from_oauth`
+already auto-creates a `Customer` on first social login, which is what shoppers expect from "Sign in
+with Google" and carries none of the staff blast radius.
+
+How IdP group claims map to Spree roles stays with the strategy, not core.
+
+**Dynamic login page (`packages/dashboard`).** `login.tsx` fetches the provider list and renders from
+it:
+
+- `email` present → the password form, as today.
+- Redirect providers present → one button each, sending the browser to `authorization_url`.
+- Both → form plus buttons, separated by a divider.
+- No `email` → buttons only, and the `/forgot-password` link is hidden (password reset is meaningless with no password).
+- Fetch fails → an error state, **not** a fallback password form. Falling back is the safer default for availability but the wrong one here: on an SSO-only shop it renders a form that cannot work.
+
+All provider labels and the divider copy go through i18next into every locale file, per the
+dashboard translation rule.
+
+### Phase 8: Remove deprecation aliases (6.1)
Breaking cleanup for 6.1 — remove the compatibility shims kept through 6.0 (all tagged "remove in Spree 6.1" in code), after sweeping any remaining first-party callers off them:
@@ -462,7 +588,9 @@ Breaking cleanup for 6.1 — remove the compatibility shims kept through 6.0 (al
## Open Questions
-None at this time.
+None at this time. The two Phase 7 questions raised on 2026-08-03 are both resolved in that phase: a
+single generic OIDC strategy ships as the reference provider (no per-vendor classes), and provider
+discovery is Admin API only in 6.0.
## References
diff --git a/packages/admin-sdk/src/admin-client.ts b/packages/admin-sdk/src/admin-client.ts
index b2e6eadfeb..15b3082b20 100644
--- a/packages/admin-sdk/src/admin-client.ts
+++ b/packages/admin-sdk/src/admin-client.ts
@@ -46,6 +46,26 @@ export interface AuthTokens {
user: AdminUser
}
+/**
+ * One authentication provider the store accepts.
+ *
+ * `password` providers are driven by the login form; `redirect` providers send
+ * the browser to `authorization_url` and come back through the OAuth callback.
+ */
+export interface AuthProvider {
+ /** Registry key, e.g. "email" or "entra". Identifies the provider on login. */
+ key: string
+ kind: 'password' | 'redirect'
+ /** Button label for redirect providers. Absent for password providers. */
+ label?: string
+ /** Where to send the browser. Absent if the provider is misconfigured or unreachable. */
+ authorization_url?: string
+}
+
+export interface AuthProvidersResponse {
+ providers: AuthProvider[]
+}
+
export interface PermissionRule {
/** true for `can`, false for `cannot` */
allow: boolean
@@ -450,6 +470,14 @@ export class AdminClient {
logout: (options?: RequestOptions): Promise<void> =>
this.request<void>('POST', '/auth/logout', options),
+ /**
+ * List the authentication providers this store accepts. Unauthenticated — it
+ * is read before a session exists, to decide whether the login page shows the
+ * password form, SSO buttons, or both.
+ */
+ providers: (options?: RequestOptions): Promise<AuthProvidersResponse> =>
+ this.request<AuthProvidersResponse>('GET', '/auth/providers', options),
+
/**
* Public (unauthenticated) lookup of a pending invitation by prefixed ID + token.
* Returns just the safe-to-render context (store, role, inviter, invitee_exists)
diff --git a/packages/admin-sdk/src/index.ts b/packages/admin-sdk/src/index.ts
index a980429a3a..9e56e0efbe 100644
--- a/packages/admin-sdk/src/index.ts
+++ b/packages/admin-sdk/src/index.ts
@@ -4,6 +4,8 @@ export type { RequestOptions, RetryConfig } from '@spree/sdk-core'
// Request infrastructure (re-export from sdk-core)
export { SpreeError } from '@spree/sdk-core'
export type {
+ AuthProvider,
+ AuthProvidersResponse,
AuthTokens,
DashboardAnalytics,
LoginCredentials,
diff --git a/packages/dashboard-core/src/locales/ar.json b/packages/dashboard-core/src/locales/ar.json
index be4b3813bc..833a6aa927 100644
--- a/packages/dashboard-core/src/locales/ar.json
+++ b/packages/dashboard-core/src/locales/ar.json
@@ -171,7 +171,14 @@
"auth": {
"login": {
"title": "مرحبًا بعودتك",
- "subtitle": "سجّل الدخول إلى حساب الإدارة"
+ "subtitle": "سجّل الدخول إلى حساب الإدارة",
+ "divider": "أو",
+ "sso_button": "المتابعة باستخدام {{provider}}",
+ "providers_error_title": "تسجيل الدخول غير متاح",
+ "providers_error_message": "تعذر تحميل خيارات تسجيل الدخول. يرجى تحديث الصفحة أو الاتصال بالمسؤول.",
+ "account_not_provisioned": "هذا الحساب غير مصرح له بالوصول إلى هذا المتجر. اطلب دعوة من المسؤول.",
+ "sso_failed": "تعذر تسجيل دخولك باستخدام هذا المزود. يرجى المحاولة مرة أخرى.",
+ "invalid_oauth_state": "انتهت صلاحية جلسة تسجيل الدخول أو أنها غير صالحة. يرجى بدء تسجيل الدخول من جديد."
},
"forgot_password": {
"link": "هل نسيت كلمة المرور؟",
diff --git a/packages/dashboard-core/src/locales/de.json b/packages/dashboard-core/src/locales/de.json
index 5dd067c6e7..32e69da122 100644
--- a/packages/dashboard-core/src/locales/de.json
+++ b/packages/dashboard-core/src/locales/de.json
@@ -171,7 +171,14 @@
"auth": {
"login": {
"title": "Willkommen zurück",
- "subtitle": "Melden Sie sich bei Ihrem Administratorkonto an"
+ "subtitle": "Melden Sie sich bei Ihrem Administratorkonto an",
+ "divider": "oder",
+ "sso_button": "Weiter mit {{provider}}",
+ "providers_error_title": "Anmeldung nicht verfügbar",
+ "providers_error_message": "Die Anmeldeoptionen konnten nicht geladen werden. Bitte laden Sie die Seite neu oder wenden Sie sich an Ihren Administrator.",
+ "account_not_provisioned": "Dieses Konto ist für diesen Shop nicht freigegeben. Bitten Sie einen Administrator um eine Einladung.",
+ "sso_failed": "Die Anmeldung mit diesem Anbieter war nicht möglich. Bitte versuchen Sie es erneut.",
+ "invalid_oauth_state": "Die Anmeldesitzung ist abgelaufen oder ungültig. Bitte melden Sie sich erneut an."
},
"forgot_password": {
"link": "Passwort vergessen?",
diff --git a/packages/dashboard-core/src/locales/en.json b/packages/dashboard-core/src/locales/en.json
index 8b49f1698c..e0116addfc 100644
--- a/packages/dashboard-core/src/locales/en.json
+++ b/packages/dashboard-core/src/locales/en.json
@@ -171,7 +171,14 @@
"auth": {
"login": {
"title": "Welcome back",
- "subtitle": "Sign in to your admin account"
+ "subtitle": "Sign in to your admin account",
+ "divider": "or",
+ "sso_button": "Continue with {{provider}}",
+ "providers_error_title": "Sign-in is unavailable",
+ "providers_error_message": "We could not load the sign-in options. Please refresh the page or contact your administrator.",
+ "account_not_provisioned": "This account is not authorized for this store. Ask an administrator for an invitation.",
+ "sso_failed": "We could not sign you in with that provider. Please try again.",
+ "invalid_oauth_state": "That sign-in session expired or was invalid. Please start signing in again."
},
"forgot_password": {
"link": "Forgot password?",
diff --git a/packages/dashboard-core/src/locales/fr.json b/packages/dashboard-core/src/locales/fr.json
index e90cacfa1f..99c9948d1d 100644
--- a/packages/dashboard-core/src/locales/fr.json
+++ b/packages/dashboard-core/src/locales/fr.json
@@ -171,7 +171,14 @@
"auth": {
"login": {
"title": "Bon retour",
- "subtitle": "Connectez-vous à votre compte administrateur"
+ "subtitle": "Connectez-vous à votre compte administrateur",
+ "divider": "ou",
+ "sso_button": "Continuer avec {{provider}}",
+ "providers_error_title": "Connexion indisponible",
+ "providers_error_message": "Impossible de charger les options de connexion. Veuillez actualiser la page ou contacter votre administrateur.",
+ "account_not_provisioned": "Ce compte n'est pas autorisé pour cette boutique. Demandez une invitation à un administrateur.",
+ "sso_failed": "Nous n'avons pas pu vous connecter avec ce fournisseur. Veuillez réessayer.",
+ "invalid_oauth_state": "Cette session de connexion a expiré ou n'était pas valide. Veuillez recommencer."
},
"forgot_password": {
"link": "Mot de passe oublié ?",
diff --git a/packages/dashboard-core/src/locales/pl.json b/packages/dashboard-core/src/locales/pl.json
index f0b363143f..191bea7e3a 100644
--- a/packages/dashboard-core/src/locales/pl.json
+++ b/packages/dashboard-core/src/locales/pl.json
@@ -171,7 +171,14 @@
"auth": {
"login": {
"title": "Witaj ponownie",
- "subtitle": "Zaloguj się do swojego konta administratora"
+ "subtitle": "Zaloguj się do swojego konta administratora",
+ "divider": "lub",
+ "sso_button": "Kontynuuj z {{provider}}",
+ "providers_error_title": "Logowanie niedostępne",
+ "providers_error_message": "Nie udało się wczytać opcji logowania. Odśwież stronę lub skontaktuj się z administratorem.",
+ "account_not_provisioned": "To konto nie ma dostępu do tego sklepu. Poproś administratora o zaproszenie.",
+ "sso_failed": "Nie udało się zalogować przez tego dostawcę. Spróbuj ponownie.",
+ "invalid_oauth_state": "Ta sesja logowania wygasła lub była nieprawidłowa. Zaloguj się ponownie."
},
"forgot_password": {
"link": "Nie pamiętasz hasła?",
diff --git a/packages/dashboard-core/src/locales/zh-CN.json b/packages/dashboard-core/src/locales/zh-CN.json
index e672e46944..7f0d054f2b 100644
--- a/packages/dashboard-core/src/locales/zh-CN.json
+++ b/packages/dashboard-core/src/locales/zh-CN.json
@@ -171,7 +171,14 @@
"auth": {
"login": {
"title": "欢迎回来",
- "subtitle": "登录您的管理员账户"
+ "subtitle": "登录您的管理员账户",
+ "divider": "或",
+ "sso_button": "使用 {{provider}} 继续",
+ "providers_error_title": "无法登录",
+ "providers_error_message": "无法加载登录选项。请刷新页面或联系管理员。",
+ "account_not_provisioned": "此账户无权访问该店铺。请向管理员申请邀请。",
+ "sso_failed": "无法使用该提供商登录,请重试。",
+ "invalid_oauth_state": "登录会话已过期或无效。请重新登录。"
},
"forgot_password": {
"link": "忘记密码?",
diff --git a/packages/dashboard/src/hooks/use-auth-providers.ts b/packages/dashboard/src/hooks/use-auth-providers.ts
new file mode 100644
index 0000000000..f9c3346621
--- /dev/null
+++ b/packages/dashboard/src/hooks/use-auth-providers.ts
@@ -0,0 +1,33 @@
+import type { AuthProvider } from '@spree/admin-sdk'
+import { adminClient } from '@spree/dashboard-core'
+import { useQuery } from '@tanstack/react-query'
+
+/**
+ * The authentication providers this store accepts, used by the login page to
+ * decide what to render.
+ *
+ * Not store-scoped: it is read before a session exists, so there is no selected
+ * store yet. Retries are disabled — a failure must surface promptly as an error
+ * state rather than leaving the sign-in screen spinning.
+ */
+export function useAuthProviders() {
+ const query = useQuery({
+ queryKey: ['auth', 'providers'],
+ queryFn: () => adminClient.auth.providers(),
+ retry: false,
+ staleTime: 5 * 60 * 1000,
+ })
+
+ const providers: AuthProvider[] = query.data?.providers ?? []
+
+ return {
+ ...query,
+ providers,
+ passwordProvider: providers.find((provider) => provider.kind === 'password'),
+ // A provider whose authorization URL could not be built is unusable, so it
+ // never becomes a button.
+ redirectProviders: providers.filter(
+ (provider) => provider.kind === 'redirect' && !!provider.authorization_url,
+ ),
+ }
+}
diff --git a/packages/dashboard/src/routes/login.tsx b/packages/dashboard/src/routes/login.tsx
index 4da3beed87..967b6f3900 100644
--- a/packages/dashboard/src/routes/login.tsx
+++ b/packages/dashboard/src/routes/login.tsx
@@ -1,20 +1,93 @@
import { zodResolver } from '@hookform/resolvers/zod'
+import type { AuthProvider } from '@spree/admin-sdk'
import { SpreeError } from '@spree/admin-sdk'
import { useAuth } from '@spree/dashboard-core'
-import { Button, Input, Label } from '@spree/dashboard-ui'
+import { Button, Input, Label, Skeleton } from '@spree/dashboard-ui'
import { createFileRoute, Link, Navigate } from '@tanstack/react-router'
import { useForm } from 'react-hook-form'
import { useTranslation } from 'react-i18next'
import { AuthShell } from '../components/spree/auth-shell'
+import { useAuthProviders } from '../hooks/use-auth-providers'
import { type LoginFormValues, loginFormSchema } from '../schemas/auth'
+/** Error code the SSO callback redirects back with when it rejects a sign-in. */
+type LoginSearch = { error?: string }
+
export const Route = createFileRoute('/login')({
component: LoginPage,
+ validateSearch: (search: Record<string, unknown>): LoginSearch =>
+ typeof search.error === 'string' ? { error: search.error } : {},
})
function LoginPage() {
const { t } = useTranslation()
- const { login, isLoading, isAuthenticated } = useAuth()
+ const { isAuthenticated } = useAuth()
+ const { error: callbackError } = Route.useSearch()
+ const {
+ passwordProvider,
+ redirectProviders,
+ isLoading: isLoadingProviders,
+ isError: providersFailed,
+ } = useAuthProviders()
+
+ if (isAuthenticated) return <Navigate to="/" replace />
+
+ return (
+ <AuthShell>
+ <div className="flex flex-col gap-2">
+ <h1 className="text-2xl font-bold">{t('admin.auth.login.title')}</h1>
+ <p className="text-sm text-muted-foreground">{t('admin.auth.login.subtitle')}</p>
+ </div>
+
+ {callbackError && <CallbackError code={callbackError} />}
+
+ <ProviderOptions
+ passwordProvider={passwordProvider}
+ redirectProviders={redirectProviders}
+ isLoading={isLoadingProviders}
+ failed={providersFailed}
+ />
+ </AuthShell>
+ )
+}
+
+function ProviderOptions({
+ passwordProvider,
+ redirectProviders,
+ isLoading,
+ failed,
+}: {
+ passwordProvider?: AuthProvider
+ redirectProviders: AuthProvider[]
+ isLoading: boolean
+ failed: boolean
+}) {
+ // Falling back to the password form would be the safer default for
+ // availability, but it is the wrong one here: on an SSO-only store it renders
+ // a form that cannot possibly work.
+ if (failed) return <ProvidersUnavailable />
+ if (isLoading) return <Skeleton className="h-40" />
+
+ return (
+ <div className="grid gap-6">
+ {passwordProvider && <PasswordLoginForm />}
+
+ {passwordProvider && redirectProviders.length > 0 && <Divider />}
+
+ {redirectProviders.length > 0 && (
+ <div className="grid gap-3">
+ {redirectProviders.map((provider) => (
+ <SsoButton key={provider.key} provider={provider} />
+ ))}
+ </div>
+ )}
+ </div>
+ )
+}
+
+function PasswordLoginForm() {
+ const { t } = useTranslation()
+ const { login, isLoading } = useAuth()
const form = useForm<LoginFormValues>({
resolver: zodResolver(loginFormSchema),
@@ -35,51 +108,107 @@ function LoginPage() {
}
}
- if (isAuthenticated) return <Navigate to="/" replace />
-
return (
- <AuthShell>
- <div className="flex flex-col gap-2">
- <h1 className="text-2xl font-bold">{t('admin.auth.login.title')}</h1>
- <p className="text-sm text-muted-foreground">{t('admin.auth.login.subtitle')}</p>
- </div>
- <form onSubmit={form.handleSubmit(onSubmit)}>
- <div className="grid gap-6">
- {errors.root && <p className="text-sm text-destructive">{errors.root.message}</p>}
- <div className="grid gap-2">
- <Label htmlFor="email">{t('admin.fields.email.label')}</Label>
- <Input
- id="email"
- type="email"
- placeholder={t('admin.fields.login.email.placeholder')}
- aria-invalid={!!errors.email || undefined}
- autoFocus={true}
- {...form.register('email')}
- />
- {errors.email && <p className="text-sm text-destructive">{errors.email.message}</p>}
- </div>
- <div className="grid gap-2">
- <div className="flex items-center justify-between">
- <Label htmlFor="password">{t('admin.fields.password.label')}</Label>
- <Link to="/forgot-password" className="text-sm underline-offset-4 hover:underline">
- {t('admin.auth.forgot_password.link')}
- </Link>
- </div>
- <Input
- id="password"
- type="password"
- aria-invalid={!!errors.password || undefined}
- {...form.register('password')}
- />
- {errors.password && (
- <p className="text-sm text-destructive">{errors.password.message}</p>
- )}
+ <form onSubmit={form.handleSubmit(onSubmit)}>
+ <div className="grid gap-6">
+ {errors.root && <p className="text-sm text-destructive">{errors.root.message}</p>}
+ <div className="grid gap-2">
+ <Label htmlFor="email">{t('admin.fields.email.label')}</Label>
+ <Input
+ id="email"
+ type="email"
+ placeholder={t('admin.fields.login.email.placeholder')}
+ aria-invalid={!!errors.email || undefined}
+ autoFocus={true}
+ {...form.register('email')}
+ />
+ {errors.email && <p className="text-sm text-destructive">{errors.email.message}</p>}
+ </div>
+ <div className="grid gap-2">
+ <div className="flex items-center justify-between">
+ <Label htmlFor="password">{t('admin.fields.password.label')}</Label>
+ <Link to="/forgot-password" className="text-sm underline-offset-4 hover:underline">
+ {t('admin.auth.forgot_password.link')}
+ </Link>
</div>
- <Button type="submit" className="w-full" disabled={isLoading}>
- {isLoading ? t('admin.actions.signing_in') : t('admin.actions.sign_in')}
- </Button>
+ <Input
+ id="password"
+ type="password"
+ aria-invalid={!!errors.password || undefined}
+ {...form.register('password')}
+ />
+ {errors.password && <p className="text-sm text-destructive">{errors.password.message}</p>}
</div>
- </form>
- </AuthShell>
+ <Button type="submit" className="w-full" disabled={isLoading}>
+ {isLoading ? t('admin.actions.signing_in') : t('admin.actions.sign_in')}
+ </Button>
+ </div>
+ </form>
+ )
+}
+
+function SsoButton({ provider }: { provider: AuthProvider }) {
+ const { t } = useTranslation()
+
+ // A full page navigation, not a fetch: the identity provider needs to own the
+ // browser for its own login screen and any MFA prompts.
+ return (
+ <Button
+ type="button"
+ variant="outline"
+ className="w-full"
+ onClick={() => {
+ if (provider.authorization_url) window.location.href = provider.authorization_url
+ }}
+ >
+ {t('admin.auth.login.sso_button', { provider: provider.label ?? provider.key })}
+ </Button>
+ )
+}
+
+function Divider() {
+ const { t } = useTranslation()
+
+ return (
+ <div className="relative text-center text-sm">
+ <span className="absolute inset-0 top-1/2 border-t" aria-hidden="true" />
+ <span className="relative bg-muted px-2 text-muted-foreground">
+ {t('admin.auth.login.divider')}
+ </span>
+ </div>
+ )
+}
+
+function ProvidersUnavailable() {
+ const { t } = useTranslation()
+
+ return (
+ <div className="grid gap-2 rounded-md border border-destructive/50 p-4">
+ <p className="font-medium text-sm">{t('admin.auth.login.providers_error_title')}</p>
+ <p className="text-sm text-muted-foreground">
+ {t('admin.auth.login.providers_error_message')}
+ </p>
+ </div>
+ )
+}
+
+/**
+ * Server error codes (`ERROR_CODES` in the Admin API) to their copy. A rejected
+ * SSO sign-in is not a failed credential check — the person proved who they are
+ * to the identity provider — so each code says what actually needs to happen.
+ * Unknown codes fall back to the generic message.
+ */
+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',
+}
+
+function CallbackError({ code }: { code: string }) {
+ const { t } = useTranslation()
+
+ return (
+ <p className="text-sm text-destructive">
+ {t(CALLBACK_ERROR_KEYS[code] ?? 'admin.auth.login.sso_failed')}
+ </p>
)
}
diff --git a/spree/api/app/controllers/concerns/spree/api/v3/authentication_strategies.rb b/spree/api/app/controllers/concerns/spree/api/v3/authentication_strategies.rb
new file mode 100644
index 0000000000..7db37f67c0
--- /dev/null
+++ b/spree/api/app/controllers/concerns/spree/api/v3/authentication_strategies.rb
@@ -0,0 +1,48 @@
+module Spree
+ module Api
+ module V3
+ # Resolves the authentication strategy a login request asked for, shared by
+ # the Store and Admin auth controllers so the unsupported-provider contract
+ # (error code, status, message) has exactly one definition.
+ #
+ # Including controllers supply the registry and user class.
+ module AuthenticationStrategies
+ extend ActiveSupport::Concern
+
+ private
+
+ # @param provider [String, nil] defaults to the +provider+ param, then :email
+ # @return [Object, nil] a strategy instance, or nil after rendering an error
+ def authentication_strategy(provider = nil)
+ provider ||= params[:provider].presence || 'email'
+
+ strategy = authentication_strategies.build(
+ provider,
+ params: params,
+ request_env: request.headers.env,
+ user_class: authentication_user_class
+ )
+
+ return strategy if strategy
+
+ render_error(
+ code: Spree::Api::V3::ErrorHandler::ERROR_CODES[:invalid_provider],
+ message: "Unsupported authentication provider: #{provider}",
+ status: :bad_request
+ )
+ nil
+ end
+
+ # @return [Spree::Authentication::StrategyRegistry]
+ def authentication_strategies
+ raise NotImplementedError, "#{self.class} must implement #authentication_strategies"
+ end
+
+ # @return [Class]
+ def authentication_user_class
+ raise NotImplementedError, "#{self.class} must implement #authentication_user_class"
+ end
+ end
+ end
+ end
+end
diff --git a/spree/api/app/controllers/concerns/spree/api/v3/error_handler.rb b/spree/api/app/controllers/concerns/spree/api/v3/error_handler.rb
index 19f86e23ea..f7e7e1450d 100644
--- a/spree/api/app/controllers/concerns/spree/api/v3/error_handler.rb
+++ b/spree/api/app/controllers/concerns/spree/api/v3/error_handler.rb
@@ -13,6 +13,10 @@ module Spree
invalid_token: 'invalid_token',
invalid_provider: 'invalid_provider',
invalid_refresh_token: 'invalid_refresh_token',
+ # Distinct from authentication_failed: the person proved who they are to
+ # the identity provider, but no account here is authorized for them.
+ account_not_provisioned: 'account_not_provisioned',
+ invalid_oauth_state: 'invalid_oauth_state',
current_password_invalid: 'current_password_invalid',
password_reset_token_invalid: 'password_reset_token_invalid',
redirect_url_not_allowed: 'redirect_url_not_allowed',
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.rb
index 46dc12f0ef..0e7895fab3 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
@@ -4,14 +4,14 @@ module Spree
module Admin
class AuthController < Admin::BaseController
include Spree::Api::V3::Admin::AuthCookies
+ include Spree::Api::V3::AuthenticationStrategies
skip_scope_check!
- rate_limit to: Spree::Api::Config[:rate_limit_login], within: Spree::Api::Config[:rate_limit_window].seconds, store: Rails.cache, only: :create, with: RATE_LIMIT_RESPONSE
- rate_limit to: Spree::Api::Config[:rate_limit_refresh], within: Spree::Api::Config[:rate_limit_window].seconds, store: Rails.cache, only: :refresh, with: RATE_LIMIT_RESPONSE
- rate_limit to: Spree::Api::Config[:rate_limit_refresh], within: Spree::Api::Config[:rate_limit_window].seconds, store: Rails.cache, only: :logout, with: RATE_LIMIT_RESPONSE
+ rate_limit to: Spree::Api::Config[:rate_limit_login], within: Spree::Api::Config[:rate_limit_window].seconds, store: Rails.cache, only: [:create, :providers, :callback], with: RATE_LIMIT_RESPONSE
+ rate_limit to: Spree::Api::Config[:rate_limit_refresh], within: Spree::Api::Config[:rate_limit_window].seconds, store: Rails.cache, only: [:refresh, :logout], with: RATE_LIMIT_RESPONSE
- skip_before_action :authenticate_admin!, only: [:create, :refresh, :logout]
+ skip_before_action :authenticate_admin!, only: [:create, :refresh, :logout, :providers, :callback]
# POST /api/v3/admin/auth/login
def create
@@ -34,6 +34,46 @@ module Spree
end
end
+ # GET /api/v3/admin/auth/providers
+ #
+ # Lists the registered authentication providers so the dashboard login
+ # page can render itself: the password form when :email is registered,
+ # a button per redirect provider. Unauthenticated — it is read before
+ # anyone can log in — so it exposes only provider keys, kinds, labels
+ # and authorization URLs.
+ def providers
+ described = Spree.admin_authentication_strategies.describe { |key| issue_oauth_state(key) }
+
+ render json: { providers: described }
+ end
+
+ # 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.
+ def callback
+ return render_invalid_state unless valid_oauth_state?
+
+ strategy = authentication_strategy(params[:provider])
+ return unless strategy
+
+ 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
+ )
+ end
+ end
+
# POST /api/v3/admin/auth/refresh
def refresh
refresh_token_value = refresh_token_from_cookie
@@ -75,26 +115,50 @@ module Spree
private
- def authentication_strategy
- provider = params[:provider].presence || 'email'
- strategy_class = Spree.admin_authentication_strategies[provider]
+ OAUTH_STATE_PURPOSE = 'spree/admin/oauth_state'.freeze
+ OAUTH_STATE_EXPIRY = 15.minutes
+
+ # Signed, self-expiring CSRF token handed to the identity provider and
+ # echoed back to the callback. Signing it means no server-side session
+ # storage — the token proves the redirect started here, and a forged or
+ # expired value fails verification.
+ #
+ # The provider key is signed into the payload so a state minted for one
+ # provider cannot be replayed against another's callback.
+ def issue_oauth_state(provider)
+ Rails.application.message_verifier(OAUTH_STATE_PURPOSE).generate(
+ { provider: provider.to_s, nonce: SecureRandom.hex(16) },
+ expires_in: OAUTH_STATE_EXPIRY
+ )
+ end
- unless strategy_class
- render_error(
- code: ERROR_CODES[:invalid_provider],
- message: "Unsupported authentication provider: #{provider}",
- status: :bad_request
- )
- return nil
- end
+ def valid_oauth_state?
+ state = params[:state]
+ return false if state.blank?
- strategy_class.new(
- params: params,
- request_env: request.headers.env,
- user_class: Spree.admin_user_class
+ # The verifier round-trips through JSON, so payload keys come back as strings.
+ payload = Rails.application.message_verifier(OAUTH_STATE_PURPOSE).verified(state)
+ return false unless payload.is_a?(Hash)
+
+ payload['provider'].to_s == params[:provider].to_s
+ end
+
+ def render_invalid_state
+ render_error(
+ code: ERROR_CODES[:invalid_oauth_state],
+ message: Spree.t('errors.messages.invalid_oauth_state'),
+ status: :unauthorized
)
end
+ def authentication_strategies
+ Spree.admin_authentication_strategies
+ end
+
+ def authentication_user_class
+ Spree.admin_user_class
+ end
+
def serializer_params
{
store: current_store,
diff --git a/spree/api/app/controllers/spree/api/v3/store/auth_controller.rb b/spree/api/app/controllers/spree/api/v3/store/auth_controller.rb
index 980bec5cbf..264678d486 100644
--- a/spree/api/app/controllers/spree/api/v3/store/auth_controller.rb
+++ b/spree/api/app/controllers/spree/api/v3/store/auth_controller.rb
@@ -3,6 +3,8 @@ module Spree
module V3
module Store
class AuthController < Store::BaseController
+ include Spree::Api::V3::AuthenticationStrategies
+
allow_guest_storefront_access!
# Tighter rate limits for auth endpoints (per IP to prevent brute force)
rate_limit to: Spree::Api::Config[:rate_limit_login], within: Spree::Api::Config[:rate_limit_window].seconds, store: Rails.cache, only: :create, with: RATE_LIMIT_RESPONSE
@@ -17,7 +19,7 @@ module Spree
# { "provider": "email", "email": "...", "password": "..." }
def create
strategy = authentication_strategy
- return unless strategy # Error already rendered by determine_strategy
+ return unless strategy # Error already rendered by authentication_strategy
result = strategy.authenticate
@@ -112,33 +114,12 @@ module Spree
}
end
- def authentication_strategy
- strategy_class = determine_strategy
- return nil unless strategy_class
-
- strategy_class.new(
- params: params,
- request_env: request.headers.env,
- user_class: Spree.customer_class
- )
+ def authentication_strategies
+ Spree.store_authentication_strategies
end
- def determine_strategy
- provider = params[:provider].presence || 'email'
-
- # Retrieve pre-loaded strategy class from configuration
- strategy_class = Spree.store_authentication_strategies[provider]
-
- unless strategy_class
- render_error(
- code: ERROR_CODES[:invalid_provider],
- message: "Unsupported authentication provider: #{provider}",
- status: :bad_request
- )
- return nil
- end
-
- strategy_class
+ def authentication_user_class
+ Spree.customer_class
end
def user_serializer
diff --git a/spree/api/config/routes.rb b/spree/api/config/routes.rb
index 85e1be324d..9e7ea9fd02 100644
--- a/spree/api/config/routes.rb
+++ b/spree/api/config/routes.rb
@@ -152,6 +152,11 @@ Spree::Core::Engine.add_routes do
post 'auth/refresh', to: 'auth#refresh'
post 'auth/logout', to: 'auth#logout'
+ # Provider discovery + SSO callback — unauthenticated; both are used
+ # before a session exists. Discovery drives the dashboard login page.
+ get 'auth/providers', to: 'auth#providers'
+ get 'auth/callback/:provider', to: 'auth#callback'
+
# Public invitation acceptance — unauthenticated; the prefixed ID +
# token in the URL act as the credential. Mounted under `auth/` so
# the issued refresh-token cookie's path matches `/auth/refresh`.
diff --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.rb
index b567218e73..12c5e74085 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
@@ -297,4 +297,216 @@ RSpec.describe Spree::Api::V3::Admin::AuthController, type: :controller do
expect(response.headers['Cache-Control']).to include('no-store')
end
end
+
+ describe 'GET #providers' do
+ let(:oidc_factory) do
+ Spree::Authentication::Strategies::OidcStrategy.configure(
+ issuer: 'https://idp.example.com',
+ client_id: 'client-id',
+ client_secret: 'client-secret',
+ redirect_uri: 'https://shop.example.com/api/v3/admin/auth/callback/entra',
+ label: 'Microsoft Entra ID'
+ )
+ end
+
+ it 'lists the email provider on a default install' do
+ get :providers
+
+ expect(response).to have_http_status(:ok)
+ expect(json_response['providers']).to eq([{ 'key' => 'email', 'kind' => 'password' }])
+ end
+
+ it 'does not require authentication' do
+ get :providers
+
+ expect(response).to have_http_status(:ok)
+ end
+
+ context 'with a redirect provider registered' do
+ before do
+ allow_any_instance_of(Spree::Authentication::Strategies::OidcStrategy).
+ to receive(:discovery_document).
+ and_return('authorization_endpoint' => 'https://idp.example.com/authorize')
+
+ Spree.admin_authentication_strategies.add(:entra, oidc_factory)
+ end
+
+ after { Spree.admin_authentication_strategies.remove(:entra) }
+
+ it 'describes it with a label and an authorization URL' do
+ get :providers
+
+ entra = json_response['providers'].find { |provider| provider['key'] == 'entra' }
+ expect(entra['kind']).to eq('redirect')
+ expect(entra['label']).to eq('Microsoft Entra ID')
+ expect(entra['authorization_url']).to start_with('https://idp.example.com/authorize?')
+ end
+
+ # Unauthenticated endpoint — it must never leak credentials or internals.
+ it 'exposes no client secret or class name' do
+ get :providers
+
+ expect(response.body).not_to include('client-secret')
+ expect(response.body).not_to include('OidcStrategy')
+ end
+ end
+
+ context 'when the email strategy is removed (SSO-only store)' do
+ before { Spree.admin_authentication_strategies.remove(:email) }
+
+ after do
+ Spree.admin_authentication_strategies.add(:email, Spree::Authentication::Strategies::EmailPasswordStrategy)
+ end
+
+ it 'omits the password provider so the login page hides the form' do
+ get :providers
+
+ expect(json_response['providers'].map { |provider| provider['key'] }).not_to include('email')
+ end
+ end
+ end
+
+ describe 'GET #callback' do
+ let!(:admin) { create(:admin_user, email: '[email protected]') }
+ let(:oidc_factory) do
+ Spree::Authentication::Strategies::OidcStrategy.configure(
+ issuer: 'https://idp.example.com',
+ client_id: 'client-id',
+ client_secret: 'client-secret',
+ redirect_uri: 'https://shop.example.com/api/v3/admin/auth/callback/entra',
+ label: 'Microsoft Entra ID'
+ )
+ end
+
+ # The state binds to the provider it was minted for, so the callback can
+ # reject one provider's state replayed against another.
+ def state_for(provider, expires_in: 15.minutes)
+ Rails.application.message_verifier('spree/admin/oauth_state').generate(
+ { provider: provider.to_s, nonce: SecureRandom.hex(16) },
+ expires_in: expires_in
+ )
+ end
+
+ let(:valid_state) { state_for('entra') }
+
+ before { Spree.admin_authentication_strategies.add(:entra, oidc_factory) }
+
+ after { Spree.admin_authentication_strategies.remove(:entra) }
+
+ def stub_claims(claims)
+ allow_any_instance_of(Spree::Authentication::Strategies::OidcStrategy).
+ to receive(:exchange_code_for_tokens).and_return('id_token' => 'signed-token')
+ allow_any_instance_of(Spree::Authentication::Strategies::OidcStrategy).
+ to receive(:verify_id_token).and_return(claims)
+ end
+
+ context 'with a verified email matching an existing admin' do
+ before do
+ stub_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
+ get :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)
+ end
+
+ it 'sets the refresh cookie' do
+ get :callback, params: { provider: 'entra', code: 'auth-code', state: valid_state }
+
+ expect(set_cookie_for('spree_admin_refresh_token')).to be_present
+ end
+
+ it 'links the SSO identity to the existing account' do
+ get :callback, params: { provider: 'entra', code: 'auth-code', state: valid_state }
+
+ expect(admin.identities.find_by(provider: 'entra', uid: 'idp-subject-1')).to be_present
+ end
+ end
+
+ context 'when the IdP does not assert a verified email' do
+ before do
+ stub_claims('sub' => 'idp-subject-1', 'email' => admin.email, 'email_verified' => 'false')
+ end
+
+ it 'refuses to claim the account' do
+ get :callback, params: { provider: 'entra', code: 'auth-code', state: valid_state }
+
+ expect(response).to have_http_status(:unauthorized)
+ expect(admin.identities).to be_empty
+ end
+ end
+
+ context 'when no account matches' do
+ before do
+ stub_claims('sub' => 'idp-subject-9', 'email' => '[email protected]', 'email_verified' => 'true')
+ end
+
+ it 'rejects with account_not_provisioned rather than creating an admin' do
+ expect {
+ get :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')
+ end
+ end
+
+ describe 'CSRF state' do
+ before do
+ stub_claims('sub' => 'idp-subject-1', 'email' => admin.email, 'email_verified' => 'true')
+ end
+
+ it 'rejects a forged state' do
+ get :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')
+ end
+
+ it 'rejects a missing state' do
+ get :callback, params: { provider: 'entra', code: 'auth-code' }
+
+ expect(response).to have_http_status(:unauthorized)
+ expect(json_response['error']['code']).to eq('invalid_oauth_state')
+ end
+
+ it 'rejects an expired state' do
+ expired = Timecop.travel(20.minutes.ago) { state_for('entra') }
+
+ get :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')
+ end
+
+ # A state minted for one provider must not authorize a different one.
+ it 'rejects a state minted for another provider' do
+ get :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')
+ end
+ end
+
+ context 'with an unregistered provider' do
+ # State is provider-bound and checked first, so a state minted for another
+ # provider is rejected before the registry is ever consulted.
+ it 'rejects another provider\'s state before looking the provider up' do
+ get :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')
+ end
+
+ it 'returns invalid_provider once the state matches' do
+ get :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')
+ end
+ end
+ end
end
diff --git a/spree/core/app/models/spree/authentication/strategies/base_strategy.rb b/spree/core/app/models/spree/authentication/strategies/base_strategy.rb
index 2118227d23..52b4d10353 100644
--- a/spree/core/app/models/spree/authentication/strategies/base_strategy.rb
+++ b/spree/core/app/models/spree/authentication/strategies/base_strategy.rb
@@ -4,12 +4,53 @@ module Spree
class BaseStrategy
attr_reader :params, :request_env, :user_class
+ class << self
+ # How a client initiates login with this strategy.
+ #
+ # +:password+ — the client posts credentials to the auth endpoint.
+ # +:redirect+ — the client sends the browser to the identity provider,
+ # which returns through the OAuth callback.
+ #
+ # Defaults to +:password+ so strategies written before provider
+ # discovery existed keep describing themselves correctly.
+ # @return [Symbol]
+ def kind
+ :password
+ end
+
+ # Human-readable provider name for the login button. Only meaningful for
+ # +:redirect+ strategies; defaults to nil so password strategies render
+ # their standard form instead of a button.
+ # @return [String, nil]
+ def label
+ nil
+ end
+ end
+
def initialize(params:, request_env:, user_class: nil)
@params = params
@request_env = request_env
@user_class = user_class || Spree.customer_class
end
+ # Where to send the browser to begin authentication. Redirect strategies
+ # must implement this; password strategies never call it.
+ #
+ # @param state [String] opaque CSRF token echoed back to the callback
+ # @return [String] the identity provider's authorization URL
+ def authorization_url(state:)
+ raise NotImplementedError, 'Redirect strategies must implement #authorization_url'
+ end
+
+ # Completes a redirect login from the identity provider's callback params.
+ # Redirect strategies must implement this; password strategies use
+ # +#authenticate+ instead.
+ #
+ # @return [Spree::ServiceModule::Result] the resolved user on success
+ def callback
+ raise NotImplementedError, 'Redirect strategies must implement #callback'
+ end
+
# Returns Result object with user on success
# @return [Spree::ServiceModule::Result]
def authenticate
diff --git a/spree/core/app/models/spree/authentication/strategies/oidc_strategy.rb b/spree/core/app/models/spree/authentication/strategies/oidc_strategy.rb
new file mode 100644
index 0000000000..b92c1cb035
--- /dev/null
+++ b/spree/core/app/models/spree/authentication/strategies/oidc_strategy.rb
@@ -0,0 +1,286 @@
+require 'net/http'
+
+module Spree
+ module Authentication
+ module Strategies
+ # Generic OpenID Connect strategy — the reference SSO provider.
+ #
+ # Configured by issuer rather than by vendor, so one class covers Microsoft
+ # Entra ID, Okta, Google Workspace, Keycloak and Auth0. Endpoints and signing
+ # keys are read from the issuer's discovery document
+ # (+.well-known/openid-configuration+), so nothing vendor-specific is hardcoded.
+ #
+ # Registered as a configured factory, which lets the same class back several
+ # providers with different issuers:
+ #
+ # Spree.admin_authentication_strategies.add(
+ # :entra,
+ # Spree::Authentication::Strategies::OidcStrategy.configure(
+ # issuer: 'https://login.microsoftonline.com/<tenant>/v2.0',
+ # client_id: ENV['ENTRA_CLIENT_ID'],
+ # client_secret: ENV['ENTRA_CLIENT_SECRET'],
+ # redirect_uri: 'https://shop.example.com/api/v3/admin/auth/callback/entra',
+ # label: 'Microsoft Entra ID'
+ # )
+ # )
+ class OidcStrategy < BaseStrategy
+ # Configured registry entry. Holds provider settings and builds a strategy
+ # instance per request, mirroring the class-level interface the registry
+ # reads for discovery (+kind+, +label+, +authorization_url+).
+ class Factory
+ attr_reader :config
+
+ def initialize(config)
+ @config = config
+ end
+
+ def build(params:, request_env:, user_class: nil)
+ OidcStrategy.new(
+ params: params,
+ request_env: request_env,
+ user_class: user_class,
+ config: config
+ )
+ end
+
+ def kind
+ :redirect
+ end
+
+ def label
+ config[:label]
+ end
+
+ # Reuses one request-less strategy for URL building. The factory lives
+ # for the process lifetime, so its discovery-document memo survives
+ # across requests — a fresh instance per call would re-read the cache
+ # (a DB query under solid_cache) on every login-page load.
+ def authorization_url(state:)
+ @url_builder ||= OidcStrategy.new(params: {}, request_env: {}, config: config)
+ @url_builder.authorization_url(state: state)
+ end
+ end
+
+ REQUIRED_OPTIONS = %i[issuer client_id client_secret redirect_uri].freeze
+
+ # Builds a registry entry for one identity provider.
+ #
+ # @param issuer [String] OIDC issuer URL (discovery is read from it)
+ # @param client_id [String]
+ # @param client_secret [String]
+ # @param redirect_uri [String] must match the value registered with the IdP
+ # @param label [String] name shown on the dashboard login button
+ # @param scope [String] space-separated scopes; must include +openid+
+ # @return [Factory]
+ def self.configure(issuer:, client_id:, client_secret:, redirect_uri:, label: nil, scope: 'openid email profile')
+ config = {
+ issuer: issuer.to_s.chomp('/'),
+ client_id: client_id,
+ client_secret: client_secret,
+ redirect_uri: redirect_uri,
+ label: label,
+ scope: scope
+ }
+
+ missing = REQUIRED_OPTIONS.select { |option| config[option].blank? }
+ raise ArgumentError, "OidcStrategy is missing required options: #{missing.join(', ')}" if missing.any?
+
+ # Derived once — the issuer is fixed for the life of a registration.
+ config[:cache_key_prefix] = "spree/oidc/#{Digest::SHA256.hexdigest(config[:issuer])}"
+
+ Factory.new(config)
+ end
+
+ attr_reader :config
+
+ def initialize(params:, request_env:, user_class: nil, config: {})
+ super(params: params, request_env: request_env, user_class: user_class)
+ @config = config
+ end
+
+ def provider
+ :oidc
+ end
+
+ # Where to send the browser to begin login.
+ # @param state [String] opaque CSRF token echoed back to the callback
+ # @return [String]
+ def authorization_url(state:)
+ query = {
+ client_id: config[:client_id],
+ response_type: 'code',
+ scope: config[:scope],
+ redirect_uri: config[:redirect_uri],
+ state: state
+ }
+
+ "#{discovery_document.fetch('authorization_endpoint')}?#{query.to_query}"
+ end
+
+ # Password login is not available through an OIDC provider — the browser
+ # redirect is the only entry point.
+ def authenticate
+ failure(Spree.t('errors.messages.oidc_requires_redirect'))
+ end
+
+ # Completes the login started by +#authorization_url+: exchanges the
+ # authorization code for an ID token, verifies it, and resolves the claims
+ # to a user.
+ # @return [Spree::ServiceModule::Result]
+ def callback
+ code = params[:code]
+ return 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 => e
+ Rails.logger.error("[Spree] OIDC callback failed for #{config[:label] || config[:issuer]}: #{e.message}")
+ failure(Spree.t('errors.messages.oidc_authentication_failed'))
+ end
+
+ private
+
+ # Resolves verified IdP claims to a user, in three steps:
+ #
+ # 1. a known identity logs in;
+ # 2. an existing account with the same **verified** email adopts the
+ # identity — this is what lets a shop switch on SSO without making
+ # existing staff log in with a password first;
+ # 3. anything else is rejected. Admin accounts never auto-provision, or
+ # 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?
+
+ identity = Spree::UserIdentity.find_by(
+ provider: registry_key,
+ uid: subject,
+ user_type: user_class.name
+ )
+ return success(identity.user) if identity
+
+ user = find_linkable_user(claims)
+ return failure(Spree.t('errors.messages.oidc_account_not_provisioned')) if user.nil?
+
+ user.identities.create!(provider: registry_key, uid: subject, info: identity_info(claims))
+ success(user)
+ 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.
+ def find_linkable_user(claims)
+ return nil unless claims['email_verified'].to_s == 'true'
+
+ email = claims['email']
+ return nil if email.blank?
+
+ user_class.find_by(email: email.downcase)
+ end
+
+ def identity_info(claims)
+ claims.slice('email', 'name', 'given_name', 'family_name', 'picture')
+ end
+
+ # The key this provider is registered under — used as UserIdentity#provider
+ # so two OIDC providers on one store stay distinct.
+ def registry_key
+ params[:provider].presence || provider.to_s
+ end
+
+ def exchange_code_for_tokens(code)
+ response = post_form(
+ discovery_document.fetch('token_endpoint'),
+ grant_type: 'authorization_code',
+ code: code,
+ redirect_uri: config[:redirect_uri],
+ client_id: config[:client_id],
+ client_secret: config[:client_secret]
+ )
+
+ raise "token endpoint returned #{response.code}" unless response.is_a?(Net::HTTPSuccess)
+
+ JSON.parse(response.body)
+ end
+
+ # Verifies signature, issuer and audience. Skipping any of these would let
+ # a token minted for another application authenticate here.
+ def verify_id_token(id_token)
+ claims, = JWT.decode(
+ id_token,
+ nil,
+ true,
+ algorithms: discovery_document.fetch('id_token_signing_alg_values_supported', ['RS256']),
+ iss: config[:issuer],
+ verify_iss: true,
+ aud: config[:client_id],
+ verify_aud: true,
+ jwks: jwks
+ )
+
+ claims
+ end
+
+ # A loader proc rather than a fetched set: the jwt gem re-invokes it with
+ # +invalidate: true+ when a token's key id is missing from the cached set,
+ # so signing keys are cached like the discovery document yet still pick up
+ # provider key rotation on the next login.
+ def jwks
+ lambda do |options|
+ Rails.cache.delete(jwks_cache_key) if options[:invalidate]
+
+ JWT::JWK::Set.new(
+ Rails.cache.fetch(jwks_cache_key, expires_in: 12.hours) do
+ JSON.parse(http_get(discovery_document.fetch('jwks_uri')))
+ end
+ )
+ end
+ end
+
+ def jwks_cache_key
+ "#{cache_key_prefix}/jwks"
+ end
+
+ def discovery_document
+ @discovery_document ||= Rails.cache.fetch("#{cache_key_prefix}/discovery", expires_in: 12.hours) do
+ JSON.parse(http_get("#{config[:issuer]}/.well-known/openid-configuration"))
+ end
+ end
+
+ def cache_key_prefix
+ config[:cache_key_prefix]
+ end
+
+ # Short timeouts because provider discovery runs on the unauthenticated
+ # login-page endpoint: Net::HTTP's 60s defaults would let one unreachable
+ # identity provider pin a request thread for a minute per call.
+ OPEN_TIMEOUT = 2
+ READ_TIMEOUT = 5
+
+ def http_get(url)
+ uri = URI(url)
+ response = http_client(uri).request(Net::HTTP::Get.new(uri))
+ raise "#{url} returned #{response.code}" unless response.is_a?(Net::HTTPSuccess)
+
+ response.body
+ end
+
+ def post_form(url, **form_data)
+ uri = URI(url)
+ request = Net::HTTP::Post.new(uri)
+ request.set_form_data(form_data)
+
+ http_client(uri).request(request)
+ end
+
+ def http_client(uri)
+ Net::HTTP.new(uri.host, uri.port).tap do |client|
+ client.use_ssl = uri.scheme == 'https'
+ client.open_timeout = OPEN_TIMEOUT
+ client.read_timeout = READ_TIMEOUT
+ end
+ end
+ end
+ end
+ end
+end
diff --git a/spree/core/app/models/spree/authentication/strategy_registry.rb b/spree/core/app/models/spree/authentication/strategy_registry.rb
index 847fe86656..d9ac2a48c7 100644
--- a/spree/core/app/models/spree/authentication/strategy_registry.rb
+++ b/spree/core/app/models/spree/authentication/strategy_registry.rb
@@ -17,6 +17,23 @@ module Spree
#
# @example Reading a strategy class
# Spree.store_authentication_strategies[:email]
+ #
+ # An entry may be either a strategy **class** or a configured **factory** —
+ # any object responding to +#build(params:, request_env:, user_class:)+.
+ # Factories let one class serve several registrations with different settings
+ # (an OIDC strategy pointed at two different issuers, say), which a bare class
+ # cannot express.
+ #
+ # @example Registering a configured factory
+ # Spree.admin_authentication_strategies.add(
+ # :entra,
+ # Spree::Authentication::Strategies::OidcStrategy.configure(
+ # issuer: 'https://login.microsoftonline.com/<tenant>/v2.0',
+ # client_id: ENV['ENTRA_CLIENT_ID'],
+ # client_secret: ENV['ENTRA_CLIENT_SECRET'],
+ # label: 'Microsoft Entra ID'
+ # )
+ # )
class StrategyRegistry
extend Forwardable
include Enumerable
@@ -67,6 +84,72 @@ module Spree
def to_h
@strategies.dup
end
+
+ # Instantiates the strategy registered under +key+, accepting either a bare
+ # class or a configured factory.
+ #
+ # @param key [Symbol, String] provider identifier
+ # @return [Object, nil] a strategy instance, or nil if no such key
+ def build(key, params:, request_env:, user_class: nil)
+ entry = self[key]
+ return nil if entry.nil?
+
+ if entry.respond_to?(:build)
+ entry.build(params: params, request_env: request_env, user_class: user_class)
+ else
+ entry.new(params: params, request_env: request_env, user_class: user_class)
+ end
+ end
+
+ # Self-description of every registered strategy, for the provider-discovery
+ # endpoint that drives the dashboard login page.
+ #
+ # Exposes only what a login screen needs — never client secrets, never
+ # strategy class names.
+ #
+ # @return [Array<Hash>] one entry per registered provider
+ # @yieldparam key [Symbol] provider key, for minting a per-provider CSRF state
+ # @return [Array<Hash>] one entry per registered provider
+ def describe
+ @strategies.map do |key, entry|
+ kind = kind_of(entry)
+ descriptor = { key: key.to_s, kind: kind.to_s }
+ descriptor[:label] = label_of(entry)
+
+ if kind == :redirect
+ state = block_given? ? yield(key) : nil
+ descriptor[:authorization_url] = authorization_url_for(entry, state: state)
+ end
+
+ descriptor.compact
+ end
+ end
+
+ private
+
+ # Registry entries predate the kind/label contract — a strategy registered
+ # before it existed (or one that does not inherit BaseStrategy) must not
+ # raise here, because describe backs the unauthenticated login page and one
+ # bad entry would take down sign-in for everyone.
+ def kind_of(entry)
+ entry.respond_to?(:kind) ? entry.kind.to_sym : :password
+ end
+
+ def label_of(entry)
+ return nil unless entry.respond_to?(:label)
+
+ entry.label.presence
+ end
+
+ # A misconfigured provider (bad issuer, unreachable discovery document)
+ # must not take down the whole login page — it drops out of the list
+ # instead, leaving the remaining providers usable.
+ def authorization_url_for(entry, state:)
+ entry.authorization_url(state: state)
+ rescue StandardError => e
+ Rails.logger.error("[Spree] Could not build authorization URL for #{label_of(entry) || entry}: #{e.message}")
+ nil
+ end
end
end
end
diff --git a/spree/core/config/locales/en.yml b/spree/core/config/locales/en.yml
index e8459366c0..ae8f70741f 100644
--- a/spree/core/config/locales/en.yml
+++ b/spree/core/config/locales/en.yml
@@ -898,6 +898,7 @@ en:
channel_store_mismatch: must belong to the same store
coupon_code_frozen_after_completion: coupon codes cannot be changed on a completed order — add a manual discount instead
delivery_zone_postal_definition_required: postal code member requires a prefix or a from/to range
+ invalid_oauth_state: Invalid or expired authentication state. Please start the sign-in again.
delivery_zone_prefix_and_range_exclusive: cannot be combined with a from/to range
delivery_zone_range_inverted: must be greater than or equal to postal_code_from
delivery_zone_range_not_supported: postal code ranges are not supported for this country — use prefixes
@@ -912,6 +913,10 @@ en:
invalid_storefront_access: is not a valid storefront access level
must_be_origin_only: must be an origin (scheme and host) without path, query, or fragment
no_pickup_point_provider: this delivery method has no pickup point provider configured
+ oidc_account_not_provisioned: This account is not authorized for this store. Ask an administrator for an invitation.
+ oidc_authentication_failed: We could not sign you in with this provider. Please try again.
+ oidc_missing_code: The identity provider did not return an authorization code.
+ oidc_requires_redirect: This provider requires signing in through its own login page.
pickup_point_not_found: pickup point could not be found with this provider
promotion_discount_not_editable: promotion discounts are managed by recalculation and cannot be edited
store_association_can_not_be_changed: The store association can not be changed
diff --git a/spree/core/spec/models/spree/authentication/strategies/oidc_strategy_spec.rb b/spree/core/spec/models/spree/authentication/strategies/oidc_strategy_spec.rb
new file mode 100644
index 0000000000..a22e28c648
--- /dev/null
+++ b/spree/core/spec/models/spree/authentication/strategies/oidc_strategy_spec.rb
@@ -0,0 +1,153 @@
+require 'spec_helper'
+
+describe Spree::Authentication::Strategies::OidcStrategy do
+ let(:issuer) { 'https://idp.example.com' }
+ let(:factory) do
+ described_class.configure(
+ issuer: issuer,
+ client_id: 'client-id',
+ client_secret: 'client-secret',
+ redirect_uri: 'https://shop.example.com/api/v3/admin/auth/callback/entra',
+ label: 'Microsoft Entra ID'
+ )
+ end
+
+ describe '.configure' do
+ it 'builds a factory describing itself as a redirect provider' do
+ expect(factory.kind).to eq(:redirect)
+ expect(factory.label).to eq('Microsoft Entra ID')
+ end
+
+ it 'raises when a required option is missing' do
+ expect {
+ described_class.configure(issuer: issuer, client_id: nil, client_secret: 's', redirect_uri: 'u')
+ }.to raise_error(ArgumentError, /client_id/)
+ end
+
+ it 'normalizes a trailing slash on the issuer so discovery URLs stay well-formed' do
+ configured = described_class.configure(
+ issuer: 'https://idp.example.com/',
+ client_id: 'c', client_secret: 's', redirect_uri: 'u'
+ )
+
+ expect(configured.config[:issuer]).to eq('https://idp.example.com')
+ end
+ end
+
+ describe '#build' do
+ it 'returns a strategy carrying the configured provider settings' do
+ strategy = factory.build(params: { code: 'abc' }, request_env: {}, user_class: Spree.admin_user_class)
+
+ expect(strategy).to be_a(described_class)
+ expect(strategy.user_class).to eq(Spree.admin_user_class)
+ expect(strategy.config[:client_id]).to eq('client-id')
+ end
+ end
+
+ describe '#authenticate' do
+ it 'refuses direct credential login' do
+ result = factory.build(params: {}, request_env: {}).authenticate
+
+ expect(result).not_to be_success
+ end
+ end
+
+ describe '#callback' do
+ let(:strategy) { factory.build(params: params, request_env: {}, user_class: Spree.admin_user_class) }
+
+ # UserIdentity validates `provider` against the registered strategy keys, so
+ # identity linking only works for a provider that is actually registered.
+ before { Spree.admin_authentication_strategies.add(:entra, factory) }
+ after { Spree.admin_authentication_strategies.remove(:entra) }
+
+ context 'without an authorization code' do
+ let(:params) { { provider: 'entra' } }
+
+ it 'fails' do
+ expect(strategy.callback).not_to be_success
+ end
+ end
+
+ context 'with verified claims' do
+ let(:params) { { provider: 'entra', code: 'auth-code' } }
+ let(:claims) do
+ { 'sub' => 'idp-subject-1', 'email' => admin.email, 'email_verified' => 'true', 'name' => 'Ada' }
+ end
+ let!(:admin) { create(:admin_user, email: '[email protected]') }
+
+ before do
+ allow(strategy).to receive(:exchange_code_for_tokens).and_return('id_token' => 'signed-token')
+ allow(strategy).to receive(:verify_id_token).with('signed-token').and_return(claims)
+ end
+
+ it 'links the identity to the existing admin and signs them in' do
+ result = strategy.callback
+
+ expect(result).to be_success
+ expect(result.value).to eq(admin)
+ expect(admin.identities.find_by(provider: 'entra', uid: 'idp-subject-1')).to be_present
+ end
+
+ it 'signs in through an already-linked identity without creating a second one' do
+ strategy.callback
+ second = factory.build(params: params, request_env: {}, user_class: Spree.admin_user_class)
+ allow(second).to receive(:exchange_code_for_tokens).and_return('id_token' => 'signed-token')
+ allow(second).to receive(:verify_id_token).and_return(claims)
+
+ expect { second.callback }.not_to change(Spree::UserIdentity, :count)
+ end
+
+ context 'when the email is not verified by the provider' do
+ let(:claims) do
+ { 'sub' => 'idp-subject-1', 'email' => admin.email, 'email_verified' => 'false' }
+ end
+
+ # Matching on an unverified claim would let anyone who can set their IdP
+ # email to a staff address take over that account.
+ it 'refuses to claim the existing account' do
+ result = strategy.callback
+
+ expect(result).not_to be_success
+ expect(admin.identities).to be_empty
+ end
+ end
+
+ context 'when no account matches the verified email' do
+ let(:claims) do
+ { 'sub' => 'idp-subject-2', 'email' => '[email protected]', 'email_verified' => 'true' }
+ end
+
+ it 'rejects rather than auto-provisioning an admin' do
+ expect { expect(strategy.callback).not_to be_success }.not_to change(Spree.admin_user_class, :count)
+ end
+ end
+ end
+
+ context 'when the provider call raises' do
+ let(:params) { { provider: 'entra', code: 'auth-code' } }
+
+ it 'returns a failure instead of propagating the error' do
+ allow(strategy).to receive(:exchange_code_for_tokens).and_raise(StandardError, 'boom')
+
+ expect(strategy.callback).not_to be_success
+ end
+ end
+ end
+
+ describe '#authorization_url' do
+ before do
+ allow_any_instance_of(described_class).to receive(:discovery_document).and_return(
+ 'authorization_endpoint' => "#{issuer}/authorize"
+ )
+ end
+
+ it 'includes the client, redirect URI and CSRF state' do
+ url = factory.authorization_url(state: 'csrf-token')
+
+ expect(url).to start_with("#{issuer}/authorize?")
+ expect(url).to include('client_id=client-id')
+ expect(url).to include('state=csrf-token')
+ expect(url).to include('response_type=code')
+ end
+ end
+end
diff --git a/spree/core/spec/models/spree/authentication/strategy_registry_spec.rb b/spree/core/spec/models/spree/authentication/strategy_registry_spec.rb
index 16a585a73e..b0e79a32a6 100644
--- a/spree/core/spec/models/spree/authentication/strategy_registry_spec.rb
+++ b/spree/core/spec/models/spree/authentication/strategy_registry_spec.rb
@@ -94,4 +94,94 @@ describe Spree::Authentication::StrategyRegistry do
expect(registry.key?(:tampered)).to be false
end
end
+
+ describe '#build' do
+ let(:buildable_class) do
+ Class.new do
+ attr_reader :params, :request_env, :user_class
+
+ def initialize(params:, request_env:, user_class: nil)
+ @params = params
+ @request_env = request_env
+ @user_class = user_class
+ end
+ end
+ end
+
+ it 'instantiates a bare class entry' do
+ registry = described_class.new(email: buildable_class)
+
+ built = registry.build(:email, params: { a: 1 }, request_env: { b: 2 }, user_class: String)
+
+ expect(built).to be_a(buildable_class)
+ expect(built.params).to eq(a: 1)
+ expect(built.user_class).to eq(String)
+ end
+
+ # A configured factory lets one strategy class back several registrations
+ # with different settings — something a bare class cannot express.
+ it 'delegates to a factory entry that responds to #build' do
+ factory = double('factory', build: :built_instance)
+ registry = described_class.new(entra: factory)
+
+ expect(registry.build(:entra, params: {}, request_env: {})).to eq(:built_instance)
+ end
+
+ it 'returns nil for an unregistered key' do
+ expect(described_class.new.build(:nope, params: {}, request_env: {})).to be_nil
+ end
+ end
+
+ describe '#describe' do
+ let(:password_strategy) { double('password strategy', kind: :password, label: nil) }
+ let(:redirect_strategy) do
+ double('redirect strategy', kind: :redirect, label: 'Entra ID', authorization_url: 'https://idp/auth?state=xyz')
+ end
+
+ it 'describes a password provider without a label or URL' do
+ registry = described_class.new(email: password_strategy)
+
+ expect(registry.describe).to eq([{ key: 'email', kind: 'password' }])
+ end
+
+ it 'describes a redirect provider with its label and authorization URL' do
+ registry = described_class.new(entra: redirect_strategy)
+
+ expect(registry.describe { 'xyz' }).to eq(
+ [{ key: 'entra', kind: 'redirect', label: 'Entra ID', authorization_url: 'https://idp/auth?state=xyz' }]
+ )
+ end
+
+ # Each redirect provider gets its own state so one cannot be replayed against
+ # another provider's callback.
+ it 'mints a state per redirect provider' do
+ registry = described_class.new(email: password_strategy, entra: redirect_strategy)
+ seen = []
+
+ registry.describe { |key| seen << key; "state-for-#{key}" }
+
+ expect(seen).to eq([:entra])
+ expect(redirect_strategy).to have_received(:authorization_url).with(state: 'state-for-entra')
+ end
+
+ it 'degrades an entry that predates the kind/label contract to a password provider' do
+ bare = Class.new
+ registry = described_class.new(legacy: bare)
+
+ expect(registry.describe).to eq([{ key: 'legacy', kind: 'password' }])
+ end
+
+ # A misconfigured or unreachable provider must not take down the login page
+ # for every other provider.
+ it 'omits the URL when building it raises, keeping other providers usable' do
+ broken = double('broken strategy', kind: :redirect, label: 'Broken')
+ allow(broken).to receive(:authorization_url).and_raise(StandardError, 'unreachable')
+ registry = described_class.new(email: password_strategy, broken: broken)
+
+ described = registry.describe
+
+ expect(described).to include({ key: 'email', kind: 'password' })
+ expect(described.last).to eq(key: 'broken', kind: 'redirect', label: 'Broken')
+ end
+ end
end