I am developing an ASP.NET Core web application that is used to exchange data between me and a third party. The app is using the Microsoft Identity Platform to authenticate users. I want to create app registration for two tenants only, so that admins of both tenants can independently create and delete web app users. Users from other tenants should not be allowed to access the app.
Here is what I have done so far:
My questions are:
This is what the AzureAd configuration looks like in the appsettings.json
file:
{
"AzureAd": {
"Instance": "[my instance]",
"Domain": "[my domain]",
"ClientId": "[my client id]",
"TenantId": "organizations",
"CallbackPath": "/signin-oidc"
},
}
This is the relevant code snippet from Startup.cs
:
services.AddAuthentication(OpenIdConnectDefaults.AuthenticationScheme)
.AddMicrosoftIdentityWebApp(Configuration.GetSection("AzureAd"));
services.AddControllersWithViews(options =>
{
var policy = new AuthorizationPolicyBuilder()
.RequireAuthenticatedUser()
.Build();
options.Filters.Add(new AuthorizeFilter(policy));
});
services.AddRazorPages()
.AddMicrosoftIdentityUI();
I agree with @Jason Pan, to allow only two tenants to access the application, make use of below code snippet.
OnTokenValidated
event to filter the tenants.TenantID
does not match then it will throw an Unauthorized Access Exception.For sample:
{
"AllowedTenants": ["tenant1", "tenant2"]
}
//get list of allowed tenants from configuration
var allowedTenants = Configuration.GetSection("AzureAd:AllowedTenants").Get<string[]>();
services.Configure<JwtBearerOptions>(
JwtBearerDefaults.AuthenticationScheme, options =>
{
var existingOnTokenValidatedHandler = options.Events.OnTokenValidated;
options.Events.OnTokenValidated = async context =>
{
await existingOnTokenValidatedHandler(context);
if (!allowedTenants.Contains(context.Principal.GetTenantId()))
{
throw new UnauthorizedAccessException("This tenant is not authorized");
}
};
});
You can use the tenant ID tid
value in the access token to permit or restrict access for specific tenants based on your requirement.
To manage users, you can grant User.ReadWrite.All
API permission to the Microsoft Entra ID application:
And pass scope as Microsoft Graph:
"DownstreamApis": {
"MicrosoftGraph": {
// Specify BaseUrl if you want to use Microsoft graph in a national cloud.
// "BaseUrl": "https://graph.microsoft.com/v1.0",
"Scopes": [ "User.Read","User.ReadWrite.All" ]
And call the Microsoft Graph APIs. Refer this GitHub blog and SO Thread by Md Farid Uddin Kiron for more detail.
References:
Restricting multi tenant application in Azure AD - Microsoft Q&A by Vasil Michev