Authentication State¶
BadgerWebAuthTools (commerce-core/.../security/BadgerWebAuthTools.java) is the single place
that answers "who is on this request, and what may they do". Controllers, extensions and security
handlers should use it rather than reading the SecurityContextHolder directly.
The API¶
| Method | Answers |
|---|---|
isLoggedIn() |
Is a real, identified principal signed in? |
amIAnAdminUser() |
Do they hold any role in ADMIN_AUTHORITIES? |
amIARegisteredUser() |
Do they hold ROLE_USER? |
hasAnyRole(String...) |
Do they hold any of these specific roles? |
getAdminRoles() |
The canonical admin role-name list |
loggedInUserName() |
The current principal's name |
Call these in Java and pass a boolean to the template. Never enumerate roles in Thymeleaf.
Anonymous is not "logged out"¶
The single most important thing to know about Spring Security here: an unauthenticated visitor
does not have a null Authentication. The filter chain installs an
AnonymousAuthenticationToken, and that token reports isAuthenticated() == true.
So this is always wrong:
// ❌ true for EVERY visitor, including anonymous ones
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
boolean loggedIn = auth != null && auth.isAuthenticated();
isLoggedIn() uses Spring's AuthenticationTrustResolver to exclude anonymous tokens, which is
the canonical way to draw this distinction:
This was a live bug: isLoggedIn() previously used the first form, so it could never return
false in a normal web request. Anonymous visitors to /forgot-password were handed the
authenticated change-password form instead of the forgot-password form.
No security context at all¶
Worker threads, scheduled tasks and anything outside the Spring Security filter chain have an
empty context and a genuinely null Authentication. The role checks are null-safe and answer
false there; they previously dereferenced getAuthentication() directly and threw
NullPointerException.
Login names are canonical¶
A site group has one login per email. User.setLoginName stores the login name trimmed and
lower-cased (User.canonicalLoginName). UserRepository's login-name finders
(findOneUserByLoginNameAndSiteGroupId, findByLoginNameAndSiteGroupId, findAllByLoginName,
findByLoginName) match whatever the capitals, so "[email protected]" signs in to, and can't
re-register, the account made as "[email protected]". Registration, password and OIDC sign-in, the
auth server, MCP and the REST JWT filter all go through those finders.
Accounts registered before this may still hold capitals; nothing rewrote them in bulk. So the finders:
- look for the canonical form or the form as typed, an exact match on the
loginNameindex; - only if neither exists, try a whole-string case-insensitive match. That scans the index, but only runs for a login that doesn't exist yet (a registration, a first OIDC visit, a typo).
UserService.findUserForSiteContext (password, OIDC and remember-me sign-in) rewrites an old-form
login name it finds, setting just loginName and emailHash, so that account takes step 1 from
then on.
- Look accounts up through those finders, never with your own query on
loginName. - Set it through
setLoginName, neverUpdate.set("loginName", ...): the setter canonicalises it and keepsemailHashin step. - Compare a signed-in principal with an account using
BadgerWebAuthTools.isLoggedInAs(user), notequalson the names. An OIDC principal carries the provider's email as sent. - Where two accounts in a group can sign in with one email (registered twice in different capitals before this), the finders return the registered, most recently active one rather than an error, until an admin merges them (Review duplicate accounts). The merge retires the login of every registered duplicate it merges.
A session works only on shops its user can use¶
Sessions for every shop are held in one Redis namespace and keyed only by the session cookie, and a
user's roles were granted on one shop's site group. So every sign-in (password form, central sign-in,
registration, remember-me) records the site group on the session (SiteBoundSession), and
SiteBoundSessionFilter, after the sign-in filters and before authorisation, signs out a session
used on a shop of another site group: the request goes on as an anonymous visitor and is sent to sign
in. Shops that share a site group share their staff, so a session works on all of them. A superadmin
has access to every shop (System › Tenants links to a shop's admin on the shop's own domain, where the superadmin signs in if
they have no session on that domain yet) and is never
refused. A signed-in session with no site group recorded (one from before this check) is signed out
once. CrossShopIsolationIntegrationTest proves it end to end over HTTP with two shops on two hosts.
There is no shared admin login¶
Until November 2026 every database had an admin account, with no site group and one password that
was the same everywhere. UserServiceImpl let it sign in on every shop, and BadgerInitialiser
recreated it at each start if it was missing. All of that is gone: the
2026-11-19-remove-shared-admin-login system update deletes the account, and an account called
admin is now an ordinary account of its own site group. Superadmins are people's own accounts
with ROLE_SUPERADMIN, set in the database, and they sign in like anyone else (central sign-in or
an emailed code). Nothing ships a password.
A new database has no superadmin, so nobody could reach System. Set
badger.bootstrap.superadmin-email (environment BADGER_BOOTSTRAP_SUPERADMIN_EMAIL; in
~/devEnv.conf for the local stack) and restart: if no account holds ROLE_SUPERADMIN,
UserService.bootstrapSuperadmin gives that email's account with no site group (made if needed,
with no password) USER, ADMIN and SUPERADMIN. Sign in to the default site with that email
and the emailed code. Once anyone is a superadmin the setting does nothing, so it is safe to leave
set. With it unset on a database with no superadmin, start-up logs a warning saying how to set it.
Remember me¶
Ticking "Remember me" on the sign-in form (storefront accounts and the back office share it) keeps the
person signed in after their 30-minute session ends. BadgerRememberMeServices runs it as a
persistent-token scheme, not a signed cookie:
- The
bdgrRMCookiecookie isuserId$series$token, with a random series and a random 128-byte token. It is host-only (noDomain),Secure,HttpOnlyandSameSite=Lax. - The account keeps each browser's login in
User.rememberMeSeriesTokens(BadgerRememberMeToken): the series, a SHA-256 of the token (never the token itself), the shop it was made on (siteId), the browser, when it was last used and when it expires (expiresAt). - How long it lasts depends on who it is for. Anyone with an admin-level role
(
BadgerWebAuthTools.isAdminUser, the same role list asamIAnAdminUser()) is remembered forbadger.security.remember-me.admin-days(default 3); everyone else forbadger.security.remember-me.customer-days(default 30). The lifetime sets the cookie's max-age and the storedexpiresAt, and each use starts it again. It is also checked against the user's roles when the cookie is presented, counted from when the login was last issued, so a login made while someone was a customer stops working three days after its last use once they become staff, and an older cookie can't outlive a shortened setting. - Each use replaces the token. An old token presented for a live series means the cookie was copied, so every login on the account is cancelled and the browser is sent to sign in.
- A login signs someone in only on the shop it was made on: not on another tenant, and not on another
shop of the same site group either. It must also be for the user the
BDGR_USRcookie names, and that user must belong to the shop's site group. The session it starts is bound like any other. - Signing out removes this browser's login; Sign out everywhere removes them all; any password change (by the customer, through a reset link, or by an admin) removes them all.
- Logins from before logins were bound to a shop sign no one in and are removed when presented.
The key. BadgerRememberMeServices.getKey() is not a cookie secret: nothing in the cookie is signed
with it. It marks the RememberMeAuthenticationTokens the services create, and Spring's
RememberMeAuthenticationProvider checks it before accepting one, in the same JVM on the same request.
SecurityConfig must pass rememberMe().key(badgerRememberMeServices.getKey()): with two different
keys the provider refuses every remember-me sign-in (after the token was already rotated) and the
person is sent to sign in. That happened from 0.63.0 until this was fixed, when the services' key was
made configurable but the security config kept its old literal. Because the key never leaves the
process, a random one per process (the default) is right, and no per-environment secret is needed;
badger.security.remember-me-key can pin it but needn't be set. RememberMeIntegrationTest checks
the wiring and the whole flow over HTTP.
Central sign-in (Badger Auth) doesn't use this: those shops send the person back through the auth server when the session ends, and the auth server keeps its own session.
Known gaps¶
These are understood and deliberately not addressed yet — check before relying on them.
loggedInUserName() returns "anonymousUser", not null¶
That is the principal name Spring gives the anonymous token. Callers that compare it against a
real login name are safe (it will never match). Callers that record it (for example
on an audit entry) will write the literal string "anonymousUser". Gate on isLoggedIn() first where that matters.
Remember-me counts as logged in¶
isLoggedIn() returns true for a RememberMeAuthenticationToken, because remember-me is a real
identity. It is not the same as "authenticated during this session", which is the stricter
question a step-up or re-authentication gate needs to ask before a sensitive action. Nothing draws
that distinction today. Use AuthenticationTrustResolver.isRememberMe(...) if you need it.
Note the interaction with AuthenticationExtension, which derives:
While isLoggedIn() was always true this was permanently false and the soft-login UI state was
unreachable. It is now live for a registered user whose security context is anonymous — worth
checking the rendered states if you touch that extension.
@ConditionalOnBean on component-scanned services¶
Several services (UserPasswordServiceImpl, SubscriptionDunningServiceImpl,
OrderEmailResendServiceImpl, the email pipeline processors and others) carry
@ConditionalOnBean(EmailService.class) while being plain @Service components.
@ConditionalOnBean is only reliable inside auto-configuration, where ordering is guaranteed. On a
component-scanned bean the condition is evaluated during scanning, when the referenced bean
definition may not be registered yet, so the result depends on scan order. It works today because
EmailServiceConfiguration is processed first, but it is load-bearing on ordering that nothing
enforces.