How can I authenticate both an ASP.NET API and an ASP.NET MVC application using Azure Authentication, and add custom claims that can be utilized in both the client and server for logic implementation?
I have an Azure app registration for an MVC application. When a user signs in to the MVC application, they receive an access token which is sent in the header to the API to get JSON data. This part is working correctly. However, I want to add custom claims to the token so that when the user accesses the API, I can include an authentication role, such as “SomeRole”. Additionally, I want to decorate the MVC app with role-based authentication. How can I achieve this?
ASP.NET MVC CODE Program.cs
builder.Services.AddAuthentication(OpenIdConnectDefaults.AuthenticationScheme)
.AddMicrosoftIdentityWebApp(options =>
{
builder.Configuration.Bind("AzureAd", options);
options.ClientSecret = "89898";
options.SaveTokens = true;
options.Events ??= new OpenIdConnectEvents();
options.Events.OnTokenValidated += async context =>
{
// var someService = context.HttpContext.RequestServices.GetRequiredService<ISomeService>();
// var someValue = await someService.SomeMethod();
context.Principal.AddIdentity(new ClaimsIdentity(new List<Claim> { new Claim("Foo", "Bar") }));
};
})
.EnableTokenAcquisitionToCallDownstreamApi(new string[] { "api://123/.default" })
.AddInMemoryTokenCaches();
ASP.NET API Code Program.cs
builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddMicrosoftIdentityWebApi(options =>
{
builder.Configuration.Bind("AzureAd", options);
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuer = true,
ValidIssuer = $"https://sts.windows.net/{builder.Configuration["AzureAd:TenantId"]}/",
ValidateAudience = true,
ValidAudience = "api://123",
ValidateLifetime = true,
ClockSkew = TimeSpan.FromMinutes(5)
};
},
options => { builder.Configuration.Bind(“AzureAd”, options); });