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.
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. 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-08-03
Summary
Two changes in one plan:
Drop Devise, own the auth stack. Spree already has a JWT-based, strategy-pattern auth system that's fully independent of Devise for the API layer. Devise is only used by the deprecated Rails admin (being replaced by React SPA in 6.0). Remove the Devise dependency entirely and make Spree's built-in auth the default —
has_secure_password, JWT tokens, pluggable strategies.Rename User → Customer.
Spree.user_class→Spree.customer_class. Default customer model becomesSpree::Customer(replacesSpree::LegacyUser).Spree.admin_user_classstays, default becomesSpree::AdminUser(replacesSpree::LegacyAdminUser). "User" is ambiguous — "customer" is what storefront users actually are.
Problem
Devise dependency
Wrong tool for headless. Devise is a full-stack Rails auth library — controllers, views, routes, Warden middleware, cookie sessions. Spree is API-first with JWT tokens. Devise provides ~5% of its surface area to Spree (password hashing, reset tokens), the rest is dead weight.
Sends the wrong signal. TypeScript developers evaluating Spree see Devise in the dependency chain and think "this is a Rails monolith." Removing it strengthens the API-first positioning.
Already built. The core auth stack is already implemented and operational:
Spree::Authentication::Strategies::BaseStrategy— pluggable strategy patternSpree::Authentication::Strategies::EmailPasswordStrategy— email+password with bcryptSpree::UserIdentity— OAuth/social login identity storage- JWT issuance and validation in API v3 controllers
- API key system (publishable
pk_*+ secretsk_*) - Password reset via
generates_token_for(Rails 7.1+)
Conditional dependency anyway. Devise is not in any gemspec — it's already optional via conditional inheritance in the legacy admin controllers (
defined?(Devise::SessionsController) ? Devise::SessionsController : ...). The legacy Rails admin is being replaced by the React SPA.
User naming
"User" is ambiguous.
Spree.user_classcould mean customer, admin, API consumer, or anyone. Every new developer asks "which user?" The model isSpree::LegacyUser— the name itself admits the problem.API already uses "customer." Store API endpoints are
/store/customers,/store/customer, the serializer isCustomerSerializer. But the model isSpree.user_class. This mismatch confuses developers.
Current State
Auth system
| Component | Status | Location |
|---|---|---|
| JWT issuance/validation | Built | api/controllers/concerns/spree/api/v3/jwt_authentication.rb |
| API key auth (pk/sk) | Built | api/controllers/concerns/spree/api/v3/api_key_authentication.rb |
| Strategy framework | Built | core/app/models/spree/authentication/strategies/base_strategy.rb |
| Email+password strategy | Built | core/app/models/spree/authentication/strategies/email_password_strategy.rb |
| OAuth identity storage | Built | core/app/models/spree/user_identity.rb |
| Password reset tokens | Built | core/app/models/concerns/spree/user_methods.rb (via generates_token_for) |
| Store API auth endpoints | Built | api/controllers/spree/api/v3/store/auth_controller.rb |
| Rate limiting | Available | Rails 7.1+ rate_limit DSL |
| Devise (legacy admin only) | Conditional | admin/app/controllers/spree/admin/user_sessions_controller.rb |
User models
| Current | Purpose | Default class |
|---|---|---|
Spree.user_class |
Storefront customer | Spree::LegacyUser |
Spree.admin_user_class |
Admin/staff user | Spree::LegacyAdminUser |
Key Decisions (do not deviate without discussion)
Auth
- Drop Devise entirely. No conditional fallbacks, no generator, no
devise_forroutes. The legacy Rails admin is gone in 6.0 (replaced by React SPA). has_secure_passwordis the foundation. Rails core, no gem dependency. Handles bcrypt hashing,authenticate(password)method, password confirmation validation.- JWT stays as-is. Short-lived access tokens, separate audiences for store (
store_api) and admin (admin_api). Already implemented and working. - Strategy pattern stays as-is.
Spree.store_authentication_strategiesandSpree.admin_authentication_strategiesfor registering custom providers. - Add refresh token support (5.4). Short-lived access JWT (15 min) + long-lived refresh token (stored in DB, rotatable, revocable). Better UX for React admin and Next.js storefront — silent refresh instead of forced re-login. Ships in 5.4 — can't wait for 6.0 because every storefront has broken session management without it.
- Rate limiting on auth endpoints. Use Rails
rate_limitDSL on login, register, and password reset endpoints. Baked in, not optional. - Account lockout after failed attempts. Track
failed_attemptsandlocked_aton Customer/AdminUser model. Simple, no Devise dependency. - Default models ship in the gem — the host app owns no auth code (2026-07-28).
Spree::CustomerandSpree::AdminUserlive inspree_corelike any other Spree model (Product,Order). The only historic reason for a host-app-owned user model was Devise —devise_forroutes and thedevise :...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 againstspree_customersor use metafields. - No authentication generators at all. Remove both
spree/authentication/devise/andspree/authentication/custom/generator directories. Theinject_into_filescaffolding 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_strategieslets developers plug in Auth0, Clerk, Firebase, LDAP, etc. by implementingBaseStrategy. - The credential stays on the user model — no separate credential table (2026-08-03).
password_digestlives onspree_customers/spree_admin_users, not onSpree::UserIdentity. Surveyed platforms are split: Vendure keepspasswordHashon aNativeAuthenticationMethodrow (STI alongsideExternalAuthenticationMethod), Medusa v2 keeps it inprovider_identity.provider_metadata, and Saleor keeps it on theUserrow (inherited from Django'sAbstractBaseUser). 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_digestis nullable,has_secure_password validations: false, andvalid_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 breakSpree.customer_classpluggability: the Path B recipe below aliasespassword_digestto 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
:emailstrategy — 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 returninvalid_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 theSpree.<name>accessor convention used bycustomer_class/base_class/tax_provider, not aSpree::Configstring preference:Spree.password_validator, defaulting toSpree::PasswordLengthValidator, registered inengine.rbliketax_provider. Assigning a differentActiveModel::Validatorreplaces the policy wholesale. NotSpree::Dependencieseither — that registry is for services and workflows you call, whereas this is a class-level policy like the otherSpree.accessors. Vendure needs a bespokePasswordValidationStrategybecause TypeScript has novalidates_with; Rails already has the extension point, and errors on:passwordreach the dashboard form through the existing 422 →mapSpreeErrorsToFormpath, 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
Spree.user_class→Spree.customer_class. Deprecation alias for one release.Spree.admin_user_classstays as-is. Model staysSpree::AdminUser, accessor staysadmin_user_class. Only the default implementation changes fromLegacyAdminUsertoAdminUser.- Default models:
Spree::CustomerandSpree::AdminUser. ReplaceSpree::LegacyUserandSpree::LegacyAdminUser. Spree::Customerincludeshas_secure_passwordand all auth concerns by default. Production-ready out of the box, not a "legacy" placeholder.Spree::AdminUserincludeshas_secure_passwordand admin auth concerns.- Prefix IDs:
cust_for Customer,adm_for AdminUser. - Concerns renamed + consolidated:
Spree::UserMethods→Spree::CustomerMethods,Spree::AdminUserMethodsstays as-is. Aliases for one release.CustomerMethodsabsorbsSpree::UserAddressandSpree::UserPaymentSource(today the generator injects all three) so a custom user class needs exactly one include —include Spree::CustomerMethods— to be a validSpree.customer_class. - Database tables stay configurable.
Spree.customer_classcan point to any model —User,Customer, whatever the app uses. The rename is about the Spree interface and defaults, not forcing a table name.
Design Details
Spree::Customer (replaces LegacyUser)
class Spree::Customer < Spree.base_class
has_prefix_id :cust
has_secure_password
include Spree::CustomerMethods # orders, addresses, payments, wishlists
include Spree::Metafields
include Spree::Metadata
has_many :identities, class_name: 'Spree::UserIdentity', as: :user, dependent: :destroy
validates :email, presence: true, uniqueness: { case_sensitive: false }
# Account security
attribute :failed_attempts, :integer, default: 0
attribute :locked_at, :datetime
def locked?
locked_at.present? && locked_at > 30.minutes.ago
end
def record_failed_attempt!
increment!(:failed_attempts)
update!(locked_at: Time.current) if failed_attempts >= 5
end
def reset_failed_attempts!
update!(failed_attempts: 0, locked_at: nil)
end
end
Spree::AdminUser (replaces LegacyAdminUser)
class Spree::AdminUser < Spree.base_class
has_prefix_id :adm
has_secure_password
include Spree::AdminUserMethods # roles, permissions, store access
include Spree::Metafields
include Spree::Metadata
has_many :identities, class_name: 'Spree::UserIdentity', as: :user, dependent: :destroy
validates :email, presence: true, uniqueness: { case_sensitive: false }
attribute :failed_attempts, :integer, default: 0
attribute :locked_at, :datetime
end
Refresh Token Model
class Spree::RefreshToken < Spree.base_class
has_prefix_id :rt
belongs_to :user, polymorphic: true # Customer or AdminUser
has_secure_token :token
validates :token, :expires_at, presence: true
scope :active, -> { where('expires_at > ?', Time.current) }
scope :expired, -> { where('expires_at <= ?', Time.current) }
attribute :expires_at, :datetime
attribute :ip_address, :string
attribute :user_agent, :string
def expired?
expires_at <= Time.current
end
def rotate!
transaction do
destroy!
self.class.create!(
user: user,
expires_at: 30.days.from_now,
ip_address: ip_address,
user_agent: user_agent
)
end
end
end
Auth API Endpoints
# Store API
POST /api/v3/store/auth/login # provider-dispatched login (email default, OAuth/SSO/custom JWT via `provider` key) → access JWT + refresh token
POST /api/v3/store/auth/refresh # refresh token → new access JWT + rotated refresh token
POST /api/v3/store/auth/logout # revoke refresh token
POST /api/v3/store/customers # register → JWT + refresh token
POST /api/v3/store/customer/password_resets # request reset email
PATCH /api/v3/store/customer/password_resets/:token # consume token, set password → JWT
# Admin API
POST /api/v3/admin/auth/login # email+password → access JWT + refresh token
POST /api/v3/admin/auth/refresh # refresh token → new access JWT
POST /api/v3/admin/auth/logout # revoke refresh token
Auth Flow
1. Customer visits storefront
2. Login: POST /auth/login { email, password }
→ EmailPasswordStrategy.authenticate(email, password, request_env)
→ Strategy returns success(customer) or failure(message)
→ Controller issues: { access_token: JWT (15 min), refresh_token: "rt_xxx" (30 days) }
3. API requests: Authorization: Bearer <access_token>
→ JwtAuthentication concern validates, sets current_customer
4. Token expires (15 min)
→ POST /auth/refresh { refresh_token: "rt_xxx" }
→ Validate refresh token, rotate it, issue new access JWT
→ Returns: { access_token: new JWT, refresh_token: "rt_yyy" (rotated) }
5. Logout: POST /auth/logout { refresh_token: "rt_xxx" }
→ Delete refresh token from DB
Configuration
Spree.configure do |config|
# Customer auth strategies (extensible)
config.store_authentication_strategies = {
email: Spree::Authentication::Strategies::EmailPasswordStrategy
# Add custom: google: MyApp::Auth::GoogleStrategy
}
# Admin auth strategies
config.admin_authentication_strategies = {
email: Spree::Authentication::Strategies::EmailPasswordStrategy
}
# JWT config
config.jwt_access_token_expiry = 15.minutes
config.jwt_secret = Rails.application.secret_key_base
# Refresh token config
config.refresh_token_expiry = 30.days
# Account lockout
config.max_failed_login_attempts = 5
config.lockout_duration = 30.minutes
end
Custom Auth Provider Example
# Using Auth0
class MyApp::Auth::Auth0Strategy < Spree::Authentication::Strategies::BaseStrategy
def provider
:auth0
end
def authenticate(email, token, request_env = {})
# Verify Auth0 JWT
payload = Auth0Client.verify(token)
user = find_user_by_email(payload['email']) ||
find_or_create_user_from_oauth(
provider: 'auth0',
uid: payload['sub'],
info: { email: payload['email'], name: payload['name'] }
)
success(user)
rescue Auth0Client::InvalidToken => e
failure(e.message)
end
end
# Register in config
Spree.configure do |config|
config.store_authentication_strategies[:auth0] = MyApp::Auth::Auth0Strategy
end
Migration Path
Phase 1: Customer/AdminUser models + has_secure_password
class CreateSpreeCustomersAndAdminUsers < ActiveRecord::Migration[7.2]
def change
# If app uses custom user tables, these aren't needed.
# For new installs using Spree defaults:
create_table :spree_customers do |t|
t.string :email, null: false
t.string :password_digest, null: false
t.integer :failed_attempts, null: false, default: 0
t.datetime :locked_at
t.jsonb :metadata
t.timestamps
end
add_index :spree_customers, :email, unique: true
create_table :spree_admin_users do |t|
t.string :email, null: false
t.string :password_digest, null: false
t.integer :failed_attempts, null: false, default: 0
t.datetime :locked_at
t.jsonb :metadata
t.timestamps
end
add_index :spree_admin_users, :email, unique: true
# Refresh tokens
create_table :spree_refresh_tokens do |t|
t.string :token, null: false
t.references :user, polymorphic: true, null: false
t.datetime :expires_at, null: false
t.string :ip_address
t.string :user_agent
t.timestamps
end
add_index :spree_refresh_tokens, :token, unique: true
add_index :spree_refresh_tokens, [:user_type, :user_id]
add_index :spree_refresh_tokens, :expires_at
end
end
Phase 2: Data migration (for existing Devise-based installs) — implemented
Two supported paths, both delivered:
Path A — move onto the gem models (default for spree-starter installs). The rake task
spree:upgrade:migrate_users_to_customers (spree/core/lib/tasks/migrate_users_to_customers.rake,
registered in the 5_6_to_6_0 upgrade manifest) copies the legacy customer table (default
spree_users, SOURCE_USER_TABLE-overridable) into spree_customers preserving primary keys so
the already-renamed customer_id FKs still resolve, mapping encrypted_password → password_digest.
Because the target is a fresh table, it copies with explicit ids and then resets the Postgres
sequence. It re-points every polymorphic reference that named the old customer class
(Spree::User → Spree.customer_class) on spree_role_users, spree_refresh_tokens,
spree_user_identities, spree_api_keys (created_by_type + revoked_by_type), and
spree_customer_group_users (whose type column was renamed user_type → customer_type); admin rows
(Spree::AdminUser) are untouched since that class name is unchanged. Admins are handled in place —
spree_admin_users keeps its table and class, so the task just backfills password_digest from the
legacy encrypted_password. It reads the legacy table by table name only (never LegacyUser,
which is gone once all phases ship). Passwords survive with zero resets as long as no Devise
pepper is configured (spree-starter default); the task aborts loudly if Devise.pepper is set, and
— since Devise is gone in 6.0 and a former pepper can't be introspected — also aborts when Devise is
absent until the operator confirms none was used (CONFIRM_NO_PEPPER=true). A preflight aborts with the
offending ids when a source row has a blank email or an email already owned by a different customer
(SKIP_INVALID_ROWS=true skips them instead) — otherwise the renamed customer_id FKs could point at a
customer that never migrated. The source table is left in place as a safety net (a later cleanup drops
it). Idempotent — re-running skips ids already in spree_customers.
Path B — keep a custom user model (documented recipe, no gem code). No data migration and no new
concern: point Spree.customer_class at the existing model, replace the old three-concern include set
with include Spree::CustomerMethods (which already absorbs UserAddress + UserPaymentSource), add
has_secure_password validations: false, and bridge the digest column on that model with
alias_attribute :password_digest, :encrypted_password (or rename the column). The alias lives on the
app model, so Spree::Customer is untouched — a blanket alias in CustomerMethods would shadow the
default model's real password_digest and break has_secure_password, which is why it stays a recipe.
Proven by spec/models/spree/legacy_encrypted_password_recipe_spec.rb. For apps with shared auth DBs,
SSO-owned user tables, or non-bcrypt setups.
Schema note: the two Phase-1 create migrations were merged into a single clash-aware
20260728000000_create_spree_customers_and_admin_users (a non-colliding name — the old
create_spree_admin_users is deduped away at install:migrations copy time and never runs on
upgrades). It creates spree_customers fresh, and for spree_admin_users guards
create … unless table_exists? + add_column :password_digest unless column_exists? (added alongside
encrypted_password, never renamed, so Devise digests survive for the backfill).
Phase 3: Rename config accessors + concerns
Spree.user_class→Spree.customer_class(deprecation alias foruser_class)Spree.admin_user_classstays as-isSpree::UserMethods→Spree::CustomerMethods(deprecation alias)Spree::AdminUserMethodsstays as-isSpree::LegacyUser→Spree::Customer(new default)Spree::LegacyAdminUser→Spree::AdminUser(new default, production-ready)- Rename
user_idFK →customer_idon 11 customer-facing tables (see decisions.md entry) - Update
belongs_to :user→belongs_to :customeron those models
Implementation notes (Phases 1 & 3):
Spree::Customer(newspree_customers, complete column set) +Spree::AdminUser(existingspree_admin_users+password_digest) both usehas_secure_password validations: falsewith a confirmation-only validation — password presence is not enforced at the model level (matches the prior LegacyUser default; storefront registration / admin-claim own that), so admin-created password-less accounts stay valid.valid_password?kept as anauthenticatealias.- Prefix IDs:
cust_(wascus) /adm_(wasadmin). Spree::UserMethods→Spree::CustomerMethods(absorbsUserAddress+UserPaymentSource); constant-alias file keeps the old name. Concern made column-agnostic: password-reset token key falls back throughpassword_salt→encrypted_password→password_digest;loginwrite guarded byhas_attribute?.- FK/association back-compat via a
Spree::DeprecatedCustomerAliasconcern (deprecateduser/user_id/:userreader+writer) included on the 10 models;spree_customer_group_usersis polymorphic souser_type→customer_typetoo. Model-scoped i18n error keys added underspree/customer. - Historical
add_*_to_spree_usersmigrations now guard ontable_exists?(Spree.customer_class.table_name)so a fresh default install (where the completespree_customersis created by its own migration) skips them cleanly, while a custom user table still gets backfilled. - The two historical
spree_admin_usersALTER migrations (add_first_and_last_name_to_spree_admin_class,add_selected_locale_to_spree_admin_users) were removed: unlike thespree_usersALTERs they carried notable_exists?guard, so on a fresh gem-owned install — where nothing createsspree_admin_usersbefore them — they aborteddb:migrate. Their columns already ship increate_spree_customers_and_admin_usersand the dummy generator, and existing installs ran them long ago. spree/adminleft untouched (removed in 6.0) — it rides the deprecatedSpree.user_classalias.- Spree's own specs use
customerdirectly, not the aliases (aliases are only to smooth external-gem migration): factory calls migrateduser:→customer:for renamed-model factories (Import/Export/Report/RoleUser/RefreshToken/StateChange/UserIdentity keepuser:),Spree.user_class→Spree.customer_class. Done acrosscore,apiandemails: the.user/.user_idreads andassociate_user!/disassociate_user!calls are migrated too, so the first-party suites no longer emit any customer-rename deprecation warning. Three call sites read a different target and were renamed accordingly —Address#user→#owner, not#customer. Genuinely non-deprecatedusernames were left alone:Spree::Core::Pricing::Context#user, the analytics handler'suser:, and the auth strategies'user_class(which holds a customer or an admin class). Spree::Cart#associate_user!was deleted rather than kept. Cart is new in 6.0, so it never had a pre-rename name to bridge; onlySpree::Orderkeeps the deprecated pair.- The
usersassociations are bridged, not left as-is.GiftCardandPromotion::Rules::Usergained a realhas_many :customers, withuserskept beside it as a Rails 8.1deprecated: truetwin;CustomerGroupalready had both, so itsuserswas simply marked. The promotion rule's hand-writtencustomer_ids/customer_ids=delegators were deleted — those now come from thecustomersassociation itself, which keeps one write path rather than two association caches over the same join rows.Role#users(paired withadmin_usersas a customer-vs-admin split) andPriceRules::UserRule#users(a plain method over auser_idspreference column, on a superseded rule) were deliberately left alone. - The Admin API takes
customer_idonly — the legacyuser_idparam is gone fromAdmin::OrdersControllerandAdmin::GiftCardsController, along withuser_idinGiftCard's Ransack allowlist, so a back-office client has one spelling. This also repairs a read/write asymmetry: the gift card serializer already returnedcustomer_idwhile the controller accepted onlyuser_id, so a client could not round-trip what it read.@spree/admin-sdkparams, the dashboard's gift-card form mapper and table filter, and the generated OpenAPI spec were updated to match. The Store API is untouched.
Phase 4: Refresh tokens, rate limiting, account lockout
Shipped earlier (5.4 + prior 6.0 work):
Spree::RefreshTokenmodel (issue/rotate/revoke) —create_for/rotate!/revoke_all_for.AuthControllerissues refresh tokens alongside access JWTs, andPOST /auth/refresh+POST /auth/logoutfor both store (refresh token in body) and admin (HttpOnly cookie).- Rate limiting (Rails
rate_limit) on login/refresh/register/password-reset + a global per-caller throttle +X-RateLimit-*headers, all config-driven viaSpree::Api::Config[:rate_limit_*]: one bucket per caller across all v3 controllers (scope: 'api_v3'), split by credential — secret keys getrate_limit_per_secret_key(600/min) per key, publishable keys getrate_limit_per_key(300/min) per key + client IP (per visitor, never per storefront), keyless/JWT traffic per IP. - Account-lockout methods +
failed_attempts/locked_atcolumns on Customer/AdminUser.
Landed:
- Account-lockout enforcement.
EmailPasswordStrategy#authenticatenow blocks locked accounts (distinct "temporarily locked" message), records a failed attempt on a bad password, and resets on success —respond_to?-guarded so a customcustomer_classwithout lockout still authenticates. One hook covers both store and admin login. - Config-driven thresholds. Lockout logic extracted into a shared
Spree::AccountLockoutconcern (included by both models) readingSpree::Config[:max_failed_login_attempts](5) and[:lockout_duration](1800s) instead of the previously hardcoded5/30.minutes. - Admin logout rate-limit added to match the store side.
- Dashboard login surfaces the server message (
@spree/dashboardlogin.tsx) so the lockout response reaches the UI instead of a generic error — bad credentials and lockout share an error code, so the message is the only distinguishing signal.
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:
# 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):
- Deleted the
spree/core/lib/generators/spree/authentication/devise/andcustom/generators (keptdummy/for the test harness). - Deleted
Spree::LegacyUserandSpree::LegacyAdminUser(4 specs repointed toSpree.customer_class). - Removed the Devise bridges —
Spree::AdminUserMethods::DeviseNotificationsandCustomerMethods::SkipPasswordValidation— plus their spec/controller callers. Live admin auth emails already flow through theadmin_user.password_reset_requestedevent subscriber; password-less admin-created customers work viahas_secure_password validations: false. - Removed the core
devise:i18n block and reworded the Devise comments. - Flipped the root-gem
spree:install--authenticationdefault tonil(a plain install scaffolds no auth — the gem owns it) and dropped the devise dispatch branch; removed thecommon_rakedevise shell-out. - Rewrote the documented
rails new -m template.rbinstall to be headless and gem-owned: drops thedeviseandspree_admingems, installs core + API only (no--authentication/--user_classflags), and removes the obsoleteProcfile.devstep (bin/devruns the server directly).USE_LOCAL_SPREEnow takes a monorepo path so the template resolves edge gems. (The spree-starter clone behindcreate-spree-app/server:setupis still Devise — that is Phase 5b.)
Deferred (NOT done here):
spree/admin's Devise controllers/generators (user_sessions_controller,user_passwords_controller,spree/admin/devise/) ride the wholesale admin-gem removal (6.0-admin-spa.md).- The
defined?(Devise)guards inspree:upgrade:migrate_users_to_customersare kept (defensive for installs migrating off Devise). No Warden references existed in core/api.
Phase 5b: spree-starter changes
The starter currently ships the host-app auth code the generator produced. At 6.0:
- Remove
app/models/spree/user.rb(the DeviseSpree::Usermodel) - Remove the
devisegem from the Gemfile - Remove
lib/spree/authentication_helpers.rband itsto_preparewiring inconfig/initializers/spree.rb - Remove
devise_forroutes and theDevise.parent_controllerinitializer block - Ship the Path A migration rake task invocation in the upgrade guide
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:userfactory alias all remain for 6.0. This supersedes the earlier "remove theuser_classalias in 6.0" plan; their removal is extracted to Phase 8 (6.1). This covers the Ruby aliases only — the Admin API'suser_idrequest param was dropped outright in 6.0 (see Phase 3), since the back-office API is a 6.0 surface with no installed base to carry. Spree::OauthAccessToken: nothing remains (extracted upstream tolegacy_api_v2). No-op. ✓- Devise /
user_classdocs sweep — done: rewrote the Devise-as-default pages (customization/authentication, admin/authentication, adding_spree_to_rails_app, customization/quickstart, admin.mdx) around the gem-ownedSpree::Customer/AdminUser+has_secure_password+ custom-model recipe, and sweptSpree.user_class→Spree.customer_classacross 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), thespree_userstable teardown task, and the search-areamulti_searchalias removal.
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:
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.
{ "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:
- Known identity — a
Spree::UserIdentitymatching(provider, uid, user_type)already exists. Log in. - Existing admin, first SSO login — no identity yet, but an
AdminUserhas the same email and the IdP assertsemail_verified: true. Link a newUserIdentityto 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. An explicitemail_verified: falseis always refused. A missing claim is a separate case (2026-08-04): Entra omits it for work accounts, so a strict reading would block first-login linking on the reference provider. Absence therefore falls to per-providertrust_unverified_email:(default off), enabled only for a directory that owns its addresses — never for a provider where a person picks their own email. - 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:
emailpresent → 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-passwordlink 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:
Spree.user_class/Spree.user_class=shims inspree/core/lib/spree/core.rb(callers move toSpree.customer_class).Spree::UserMethods = CustomerMethodsalias (spree/core/app/models/concerns/spree/user_methods.rb).Spree::DeprecatedCustomerAlias— the deprecateduser/user_idreaders + writers — from the 10 customer-facing models.- The
:useralias on the:customerfactory (spree/core/lib/spree/testing_support/factories/user_factory.rb).
Constraints on Current Work
- Don't add new Devise dependencies. No new
devise_for, no new Devise controller inheritance. - Use
Spree.user_class/Spree.admin_user_classfor now —user_classwill becomecustomer_classin 6.0,admin_user_classstays. - New auth features should use the strategy pattern. Don't bypass
BaseStrategyfor auth logic. - JWT tokens are the only API auth mechanism. No cookie sessions in API controllers.
Open Questions
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
- Current auth strategy:
spree/core/app/models/spree/authentication/strategies/base_strategy.rb - Current JWT implementation:
spree/api/app/controllers/concerns/spree/api/v3/jwt_authentication.rb - Current user models:
spree/core/app/models/spree/legacy_user.rb,spree/core/app/models/spree/legacy_admin_user.rb - Current user concerns:
spree/core/app/models/concerns/spree/user_methods.rb,spree/core/app/models/concerns/spree/admin_user_methods.rb - Devise generators (to be removed):
spree/core/lib/generators/spree/authentication/devise/ - Related plan:
6.0-admin-spa.md(React admin removes Rails admin, kills Devise dependency) - Related plan:
6.0-channels-catalogs-b2b.md(Company → CompanyContact references customer/staff)