Authentication is hard. Multi-tenant authentication is harder.
Here is the scenario: You have a B2B SaaS application.
- You have your Internal Staff (Support, Ops, etc.) who live in your corporate Azure AD tenant.
- You have your External Customers, who might be logging in via their own methods, or perhaps a separate Multi-Tenant Azure AD configuration.
You want a single API to serve both. Internal users should be able to do admin tasks; external customers should only see their own data. Sounds simple, right?
Well, technically it is, but finding the right documentation can be a nightmare.
The Solution: Multiple Authentication Schemes
ASP.NET Core (and .NET 9 broadly) handles this surprisingly well. You can register multiple JWT Bearer handlers and then use Authorization Policies to pick the right one.
Here is how we set this up.
Step 1: Registering the Schemes
In your Program.cs, you don’t just call AddJwtBearer once. You call it twice (or more), each time with a unique Scheme Name.
|
|
Step 2: Defining the Policies
Now comes the fun part. We define clear policies that specify which schemes are valid for them.
|
|
Step 3: Protecting the Endpoints
Finally, in your Controllers, you just use the standard [Authorize] attribute with your custom policy names.
|
|
Conclusion
This approach saves you from the mess of trying to merge two different identity providers into one logical “User”. It keeps the concerns separate, the configuration clean, and I can finally sleep at night knowing my internal admin endpoints are safe.