Blazor Web App Server Side .NET 8 .AddMicrosoftAccount not returning Azure App Roles
I have successfully created a Blazor Web App Server Side, and I am able to authenticate with Azure AD using the .AddMicrosoftAccount()
builder.Services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
.AddCookie()
.AddMicrosoftAccount(config =>
{
builder.Configuration.GetSection(“Authentication:Microsoft”).Bind(config);
config.Events = new Microsoft.AspNetCore.Authentication.OAuth.OAuthEvents
{
OnCreatingTicket = async context =>
{
var user = context.Principal;
var claimIdentity = user.Identity as ClaimsIdentity;
var rolesClaim = user.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Role);
var role = user.IsInRole(“Admin”);
if (rolesClaim != null)
{
var claims = rolesClaim.Value.Split(new[] { ‘|’ }, StringSplitOptions.RemoveEmptyEntries);
foreach (var claim in claims)
{
claimIdentity.AddClaim(new Claim(ClaimTypes.Role, claim));
}
}
await Task.CompletedTask;
}
};
});
But it’s not returning the roles claim with the attached roles for the user. The roles are setup correctly in Azure.
I’ve searched high and low on the internet for something that would give me a clue as to where to go. I’ve tried using OpenId, and the roles get returned there, but I can’t seem to use them in components.
How do I get these roles using the .AddMicrosoftAccount() method?
I have successfully created a Blazor Web App Server Side, and I am able to authenticate with Azure AD using the .AddMicrosoftAccount()builder.Services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
.AddCookie()
.AddMicrosoftAccount(config =>
{
builder.Configuration.GetSection(“Authentication:Microsoft”).Bind(config);
config.Events = new Microsoft.AspNetCore.Authentication.OAuth.OAuthEvents
{
OnCreatingTicket = async context =>
{
var user = context.Principal;
var claimIdentity = user.Identity as ClaimsIdentity;
var rolesClaim = user.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Role);
var role = user.IsInRole(“Admin”);
if (rolesClaim != null)
{
var claims = rolesClaim.Value.Split(new[] { ‘|’ }, StringSplitOptions.RemoveEmptyEntries);
foreach (var claim in claims)
{
claimIdentity.AddClaim(new Claim(ClaimTypes.Role, claim));
}
}
await Task.CompletedTask;
}
};
}); But it’s not returning the roles claim with the attached roles for the user. The roles are setup correctly in Azure. I’ve searched high and low on the internet for something that would give me a clue as to where to go. I’ve tried using OpenId, and the roles get returned there, but I can’t seem to use them in components. How do I get these roles using the .AddMicrosoftAccount() method? Read More