I have a .Net Core 3 API that properly authorizes and authenticates the tokens passed to it via Azure AD B2C. It also has a little bit of custom code built to check the scopes passed in the JWT token to confirm access to endpoints. (I'm using the Microsoft.AspNetCore.Authentication.AzureADB2C.UI package) Here's the block of middleware that makes this possible:
services.AddAuthentication(AzureADB2CDefaults.BearerAuthenticationScheme)
.AddAzureADB2CBearer(options => Configuration.Bind("AzureAdB2C", options));
var issuer = $"https://{Configuration["AzureAdB2C_Custom:TenantB2CHost"]}/{Configuration["AzureAdB2C:Domain"]}/v2.0/";
services.AddAuthorization(options =>
{
options.AddPolicy("api_read", policy => policy.Requirements.Add(new HasScopeRequirement("api_read", issuer)));
options.AddPolicy("api_write", policy => policy.Requirements.Add(new HasScopeRequirement("api_write", issuer)));
});
This all seems to be working to gaining access to endpoints properly. These endpoints then expose various information from my SQL database in a model.
However, now I'm trying to bring home the other aspect of my security, by controlling access to particular parts of the data retrieved in these endpoints, based on who the JWT token is actually tied to in my database.
In my particular case, I have an Accounts table, where I can store the ObjectID from Azure AD B2C that's found in the JWT token and then obtain the Account using that ObjectID at the time of calling. I could just do this at the top of an endpoint, but I suspect that this is not the best way to do it. It seems like I should be building this at the middleware layer in Startup as some kind of handler.
Can someone confirm for me that this would be the right approach and possibly give me an example of this or at least point me in the right direction?