Scrivio Interview library
ScenarioAdvanced7 min read · updated 12 November 2026

Your B2B SaaS product must support SAML SSO for 300 enterprise customers, each with their own IdP. Design the multi-tenant SAML setup.

We give every customer its own RelyingPartyRegistration, store those registrations in a database and serve them through a custom RelyingPartyRegistrationRepository with a cache. Users are routed to their tenant's IdP by subdomain, by the email domain they type on the login page, or by a registration id in the URL. Around that core we build self-service onboarding with validation and test logins, just-in-time provisioning plus SCIM for the user lifecycle, per-tenant role mapping, and per-tenant monitoring of errors and certificate expiry.

Why this question is asked

Enterprise customers rarely accept a separate password for a SaaS product. Their security teams want users to log in through their own identity provider, and SAML is still the most common way. One customer is a configuration file; 300 customers, each with its own IdP, certificates and attribute names, is a product feature with its own operations. Interviewers use this question to see whether we can scale a protocol integration into a platform. In this answer, we will recap what Spring Security needs per IdP, design the storage and lookup of registrations, choose how users find their tenant, walk through onboarding and the user lifecycle, and end with operations and the build versus buy question.

1A Quick Recap: One Registration per IdP

In Spring Security, the trust between our application (the service provider) and one identity provider is described by a RelyingPartyRegistration. It holds a registration id, our entity id and assertion consumer service URL, and the asserting party details: the IdP's entity id, its single sign-on URL and the certificates we use to verify its signatures. Spring Security finds the registration through a RelyingPartyRegistrationRepository, and its URLs carry the id, for example /saml2/authenticate/{registrationId} to start a login and /login/saml2/sso/{registrationId} to receive the response.

The default repository, InMemoryRelyingPartyRegistrationRepository, is fine for a few registrations known at startup. With 300 tenants, added and changed every week by customers themselves, the registrations must live in a database and be loaded on demand.

2Storing and Loading Registrations per Tenant

We keep one row per tenant with the registration id, the tenant id, the uploaded IdP metadata XML, any overrides, an enabled flag and audit columns. A custom repository turns that row into a RelyingPartyRegistration and caches the result, because building a registration from metadata means parsing XML and certificates, and we do not want that on every login.

Java
@Component
class TenantRelyingPartyRegistrations implements RelyingPartyRegistrationRepository {
private final SamlTenantConfigRepository configs;
private final Cache<String, RelyingPartyRegistration> cache = Caffeine.newBuilder()
.expireAfterWrite(Duration.ofMinutes(10)) // edits show up within 10 minutes
.maximumSize(1_000)
.build();
TenantRelyingPartyRegistrations(SamlTenantConfigRepository configs) { this.configs = configs; }
@Override
public RelyingPartyRegistration findByRegistrationId(String registrationId) {
return cache.get(registrationId, this::load); // null when unknown or disabled
}
private RelyingPartyRegistration load(String id) {
SamlTenantConfig c = configs.findByRegistrationIdAndEnabledTrue(id).orElse(null);
if (c == null) return null; // Spring Security answers with an error
return RelyingPartyRegistrations
.fromMetadata(new ByteArrayInputStream(c.metadataXml()))
.registrationId(id)
.entityId("{baseUrl}/saml2/service-provider-metadata/{registrationId}")
.assertionConsumerServiceLocation("{baseUrl}/login/saml2/sso/{registrationId}")
.build();
}
void evict(String id) { cache.invalidate(id); } // called when an admin edits the tenant
}

Notice the placeholders {baseUrl} and {registrationId}. Spring Security resolves them per request, so one code path serves every tenant and every subdomain. We also evict the cache entry when a tenant admin uploads new metadata, so the change is immediate rather than waiting for expiry. Our own SP signing key can be shared or per tenant; per tenant costs more key management but lets us rotate one customer without touching the others.

3How Does a User Find the Right IdP?

Before redirecting anyone, we must know which tenant they belong to. There are three common answers, and most products support more than one.

Ways to discover the tenant
MethodExampleTrade-off
Subdomainacme.app.example.comSeamless; needs wildcard DNS and TLS
Email domain on login pagejo@acme.com -> acmeFamiliar; domains must be verified per tenant
Registration id in URL/saml2/authenticate/acmeSimplest; good for IdP-initiated and bookmarks
Many products resolve the subdomain first and fall back to asking for the email address.

The email domain route has a security catch. A tenant must prove it owns a domain, typically with a DNS TXT record, before we route that domain to its IdP. Otherwise a malicious customer could register a competitor's domain and capture its users' login attempts. Whatever method we use, the outcome is the same: we redirect to /saml2/authenticate/{registrationId} and Spring Security takes over.

4Self-Service Onboarding Without Self-Service Outages

With 300 customers, our support team cannot hand-edit configuration for each. So the tenant admin page lets a customer upload their IdP metadata file or URL, shows our SP metadata for their IdP team to import, and walks them through attribute mapping.

Every upload is validated before it is saved: the XML must parse, it must contain a signing certificate, the certificate must not be expired or expire within 30 days, and the entity id must not already belong to another tenant. Then the registration is saved disabled, and the admin runs a test login from a special link. Only when a test login succeeds and the mapped attributes look right does the admin enable SSO for everyone. Keeping a password or magic-link fallback for one break-glass admin per tenant avoids a lockout if their IdP breaks.

Step throughOnboarding a tenant's IdP
  1. Admin uploads IdP metadatafile or URL
  2. Metadata and certificate valid?
    YesSave as disabledNoShow the exact problem
  3. Admin maps attributes and groupsemail, name, groups -> roles
  4. Test login succeeded?
    YesEnable SSO for the tenantNoShow the SAML error code
  5. Monitor logins and expiryper tenant dashboards

5 steps in order. Play them, or step through them one at a time.

5Users, Provisioning and Roles

SAML only authenticates. It does not create users in our database, and it never tells us when someone leaves the company. Just-in-time provisioning handles the first part: on a successful login for an unknown user, we create the account from the assertion's attributes. For the second part, enterprise customers expect SCIM 2.0, a standard REST API their IdP calls to create, update and deactivate users and groups. Without SCIM, a person fired on Monday keeps an active account in our product until someone notices, which is exactly the kind of finding their auditors report.

Role mapping is per tenant, because one customer sends a groups attribute with values like CN=Finance,OU=Groups while another sends role=approver. We store a mapping table per tenant from their group values to our roles, apply it in a custom converter on the authentication result (the OpenSaml authentication provider lets us set a response authentication converter), and default to the lowest role when nothing matches.

6Operating 300 Federations, or Buying Them

Each tenant is a separate integration that can break on its own schedule. We tag every SAML log line and metric with the tenant id and the error code, so a dashboard shows that tenant 214 has had 40 invalid_signature errors in the last hour while everyone else is fine. A daily job reads every stored certificate and alerts both us and the tenant admin 60 and 14 days before expiry, which prevents most of the outages that otherwise land on our support desk.

Finally, the honest design question: should we build this at all? Brokers such as Keycloak, or commercial identity platforms aimed at B2B SaaS, already handle per-tenant SAML, SCIM, metadata refresh and admin portals. Our application then speaks one OIDC connection to the broker. Building it ourselves gives full control and no per-connection fees, but costs a team's ongoing time. For 300 customers I would seriously price the bought option first, and build only if SSO is a core differentiator for us.

7Follow-up questions

Should all tenants share one SP entity id?

It is possible, but per-tenant entity ids, such as one including the registration id, are easier to operate. Some IdPs only allow one trust per entity id, and per-tenant ids let us rotate SP keys and debug one customer without affecting the others.

How do you support IdP-initiated login, where the user starts from their IdP portal?

The response arrives at /login/saml2/sso/{registrationId}, so the registration id in the URL already tells us the tenant. IdP-initiated login has no request to match the response against, which makes it weaker against some replay and injection attacks, so we allow it only for tenants who need it and keep assertion lifetimes short.

What happens to sessions when SCIM deactivates a user?

Deactivation should also end active sessions, otherwise the user keeps working until the session expires. We store sessions in a way we can query by user, for example Spring Session with a principal name index, and delete them when the SCIM call arrives.

8Conclusion

In this answer, we designed multi-tenant SAML around one RelyingPartyRegistration per tenant, stored in a database and served by a cached custom repository. We chose tenant discovery by subdomain, verified email domain or registration id, built onboarding that validates metadata and requires a test login before enabling, and covered just-in-time provisioning, SCIM and per-tenant role mapping. We finished with per-tenant monitoring and the real option of buying the whole capability from an identity broker.

What to say in the interviewAbout 80 seconds aloud

Open with

I would model each customer's IdP as its own RelyingPartyRegistration, stored in a database table with the tenant id, the uploaded metadata and an enabled flag, and I would implement RelyingPartyRegistrationRepository to load registrations by id with a cache that I evict when a tenant edits its settings.

Then, if they want more

Users would reach the right IdP by subdomain, or by typing their email on our login page, where the domain must be verified with a DNS record before we route it, and in the end we redirect to the registration's authenticate URL.

Onboarding would be self-service: customers upload metadata, we validate the XML and certificates, save it disabled, and they must complete a test login before enabling SSO, keeping one break-glass admin. For users, I would do just-in-time provisioning from assertion attributes, support SCIM so their IdP can deactivate leavers, and keep a per-tenant mapping from their groups to our roles.

Operationally, every metric and log carries the tenant id and SAML error code, and a daily job warns about certificates expiring within 60 days. And before building all of this, I would compare it with putting a broker like Keycloak or a commercial B2B identity service in front, because that capability is often cheaper to buy than to run.

About this answer

Last updated
12 November 2026
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Official documentation
Spring Security reference
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "Your B2B SaaS product must support SAML SSO for 300 enterprise customers, each with...": https://scrivio-interview-library.netlify.app/spring-boot/authentication/dd14d9cae6/