Enterprise SSO: SAML, OIDC and SCIM for B2B SaaS
On this page
Learning Objective
Let each customer organization sign in with its own identity provider using OIDC or SAML, identify users by stable issuer and subject instead of email, provision and deprovision users with SCIM, and avoid the well-known SAML and claim-trust vulnerabilities.
Concept Explanation
When your product sells to companies, the buyers' security teams ask for single sign-on with the identity provider they already run, such as Entra ID or Okta. Employees then sign in with their corporate account, the company controls password policy and multi-factor authentication, and access disappears when the employee leaves. This is federation, and it differs from Day 45's sign-in with an external provider in one way that matters: there is not one provider but one per customer, configured by that customer's administrator. Your data model gains a tenant identity configuration: which protocol the tenant uses, its issuer, keys or metadata, the email domains it owns, and whether SSO is mandatory.
Two protocols dominate. OpenID Connect is the modern option and has been the subject of the previous lessons. SAML 2.0, an XML-based standard from the early 2000s, is still what many enterprises require. The user starts at your app, the app redirects them to their identity provider with an authentication request, and the provider returns a signed assertion to your assertion consumer service. The flow initiated by your application is called service-provider initiated, and you should prefer it, since the identity-provider initiated variant, where the provider posts an unsolicited assertion, cannot be tied to a request you made and is easier to abuse. Discover which provider to use from the email domain the user types, called home realm discovery, and only for domains the tenant has proven it owns, using a DNS TXT record challenge, since otherwise one customer could claim another's domain.
SAML has a history of serious implementation flaws, mostly in XML signature handling. In 2018 researchers at Duo Labs showed that several widely used SAML libraries could be tricked, for example by inserting an XML comment into a user name, into reading a different identity than the one signed. Signature wrapping attacks add unsigned content that the application reads while a valid signature covers a different part. The rule is to use a well-maintained library and never parse SAML yourself, to require that the signature covers the assertion you actually use, and to validate the issuer, the audience restriction that names your service, the InResponseTo value matching your request, the validity window, and to reject replays of an assertion id that was already used. Pin the provider's signing certificate from metadata and plan for its rotation.
The most damaging mistake is trusting the wrong claim as identity. If your application uses the email address to link a federated login to an account, an attacker who controls an identity provider that lets its users set any email, or a mutable email attribute, can log in as someone else. In 2023 researchers described this as the nOAuth issue in applications that used the email claim from Microsoft Entra ID as a unique identifier, since that attribute could be changed by a tenant administrator. Identify users by the combination of the issuer, or tenant id, and the immutable subject identifier, and treat the email as unverified profile data, unless the issuer is proven to control that domain. Also configure the identity provider trust so that a tenant's users can only be created inside that tenant.
The second half of enterprise identity is provisioning. Just-in-time creation at first login is simple, but it does not remove users when they leave. SCIM 2.0, defined in RFC 7643 and 7644, is a REST standard through which the customer's identity provider creates, updates, and deactivates users and groups in your system automatically. Deprovisioning is the security-critical part: when a person is deactivated, revoke their sessions and tokens, not just mark the row. Map identity provider groups to your roles, authenticate the SCIM endpoint with a per-tenant secret token that is stored hashed, limit what it can do to that tenant, and log every change. Offer options to enforce SSO by disabling password sign-in for the tenant, keep a documented break-glass administrator, and honor session length and reauthentication policies.
| Topic | Guidance | Reason |
|---|---|---|
| Protocol | OIDC where possible, SAML when required | SAML is common in enterprises, more error-prone |
| Flow | Service-provider initiated with a request id | Assertions tie to a request you made |
| Domain ownership | DNS TXT verification before enabling home realm discovery | Prevents claiming another company's domain |
| User identity | Issuer or tenant id plus subject, never email alone | Emails can be changed or spoofed |
| Provisioning | SCIM with per-tenant token, deactivate and revoke sessions | Leavers lose access promptly |
| Enforcement | Option to require SSO, break-glass admin | Removes the weaker password path |
Worked Example: Per-Tenant Issuer Validation, Identity Linking by Subject and a SCIM Deactivation
The code validates tokens from a set of allowed tenants, links accounts safely, and handles SCIM deprovisioning.
// Multi-tenant OIDC: accept tokens only from issuers that a tenant's administrator configured and verified.
builder.Services.AddSingleton<ITenantDirectory, TenantDirectory>();
builder.Services.AddAuthentication().AddJwtBearer();
builder.Services.AddOptions<JwtBearerOptions>(JwtBearerDefaults.AuthenticationScheme)
.Configure<ITenantDirectory>((o, tenants) =>
{
o.TokenValidationParameters = new TokenValidationParameters
{
ValidAudience = "api://taskboard",
ValidateIssuerSigningKey = true,
IssuerValidator = (issuer, _, _) => tenants.IsKnownIssuer(issuer)
? issuer
: throw new SecurityTokenInvalidIssuerException($"Unknown issuer {issuer}"),
// Signing keys come from each issuer's own metadata, resolved per issuer and cached.
IssuerSigningKeyResolver = (_, _, _, parameters) => tenants.SigningKeysFor(parameters.ValidIssuer),
};
});
// Identity: the immutable pair (issuer, subject) identifies the person. Email is a profile field, not a key.
public async Task<AppUser> ResolveUserAsync(ClaimsPrincipal external, CancellationToken ct)
{
var issuer = external.FindFirstValue("iss")!;
var subject = external.FindFirstValue("sub") ?? external.FindFirstValue("oid")!;
var link = await db.ExternalLogins.Include(l => l.User).SingleOrDefaultAsync(l => l.Issuer == issuer && l.Subject == subject, ct);
if (link is not null) return link.User;
var tenant = await tenants.ForIssuerAsync(issuer, ct) ?? throw new AuthenticationFailureException("Unknown tenant");
// JIT creation happens inside the tenant that owns this issuer. We never attach a login to an existing account by matching email.
var user = new AppUser { TenantId = tenant.Id, Email = external.FindFirstValue("email"), EmailVerified = false, DisplayName = external.FindFirstValue("name") };
db.ExternalLogins.Add(new ExternalLogin { User = user, Issuer = issuer, Subject = subject });
await db.SaveChangesAsync(ct);
return user;
}// SCIM: the customer's identity provider deactivates a user. We revoke access, not just flip a flag.
app.MapPatch("/scim/v2/Users/{id:guid}", async (Guid id, ScimPatch patch, HttpContext ctx, AppDb db, ISessionRevoker revoker, CancellationToken ct) =>
{
var tenantId = ctx.GetTenantFromScimToken(); // per-tenant bearer token, stored hashed
var user = await db.Users.SingleOrDefaultAsync(u => u.Id == id && u.TenantId == tenantId, ct); // a tenant token can touch only its own users
if (user is null) return Results.NotFound();
foreach (var op in patch.Operations.Where(o => o.Path == "active"))
{
user.IsActive = op.Value.GetBoolean();
if (!user.IsActive)
{
await revoker.RevokeAllSessionsAsync(user.Id, ct); // cookies and refresh tokens end now
await revoker.RevokeApiKeysAsync(user.Id, ct);
}
}
await db.SaveChangesAsync(ct);
await audit.WriteAsync("scim.user.updated", user.Id, tenantId, ct);
return Results.Ok(ScimUser.From(user));
}).RequireAuthorization("ScimTenantToken");SAML response validation checklist (done by the library, verified by you in tests)
1. The XML signature covers the assertion that is read, and the signing certificate matches the tenant's pinned metadata.
2. Issuer equals the configured entity id for this tenant.
3. Audience restriction contains our entity id.
4. InResponseTo matches an authentication request we issued in this session (for SP-initiated flows).
5. NotBefore and NotOnOrAfter are valid, with a small skew.
6. The assertion id has not been seen before (replay cache).
7. The subject name id is used as an identifier only together with the issuer, and comments in it do not change its value.
Domain verification for a tenant: create TXT record _taskboard-verify.acme.com = <random token we generated>Tests for this area should include forged assertions: an unsigned one, one signed by another tenant's key, one with a changed audience, and one replayed. Each must fail, and each has been the cause of a real vulnerability somewhere.
Real-World Examples
- In February 2018 researchers at Duo Labs disclosed a family of vulnerabilities in SAML implementations in several languages, in which inserting an XML comment into the user name allowed an attacker with a valid account to authenticate as another user, because the signature verification and the identity extraction interpreted the value differently. Multiple libraries were patched, and the incident is the standard reason not to write your own SAML processing.
- In 2023 researchers at Descope described the nOAuth misconfiguration, where applications using the email claim from Microsoft Entra ID as a user identifier could be taken over by an attacker who set the email on their own tenant's account to a victim's address. Microsoft and the researchers advised using the subject or object identifier as the unique key, which is the design in this lesson.
Review Questions & Answers
An email address can be set or changed by whoever administers an identity provider, so matching on it lets an attacker sign in as the victim. The issuer and subject pair is stable and unique to a person at that provider.
Without it, any customer could register another company's email domain and receive that company's users' sign-ins, or capture their accounts. A DNS TXT challenge proves the tenant controls the domain.
It removes access automatically when the customer's identity provider deactivates a person, so leavers do not keep working accounts. It must also revoke sessions and tokens, not only mark the user inactive.
The authentication request carries an id that the response must reference, which ties the assertion to a request made in that browser session. Unsolicited provider-initiated assertions cannot be tied to a request and are easier to inject or replay.