I'm creating an asp net core 2 web api using azure AD B2C for authentification. I would like to use AD B2C groups to restrict the use of some controllers to admin members.
I've understood that for the moment the only way to achieve that is to access graph api and add to user's claims some role claims.
But I'm having troubles querying graph api in my startup.
My ConfigureService
method looks like this :
services.AddAuthentication(sharedOptions =>
{
sharedOptions.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
sharedOptions.DefaultChallengeScheme = OpenIdConnectDefaults.AuthenticationScheme;
})
.AddAzureAdB2C(options => Configuration.Bind("AzureAdB2C", options))
.AddJwtBearer(options => {
options.Authority = string.Format("https://login.microsoftonline.com/tfp/{0}/{1}/v2.0/", "b2ctenant.onmicrosoft.com", "B2C_1_DefaultSignUpIn");
options.Audience = "xxxxxxx-xxxx-xxxx-xxxx-xxxxxxxx";
options.Events = new JwtBearerEvents
{
OnTokenValidated = OnAuthorizationCodeReceived,
};
})
.AddCookie(options =>
{
options.LoginPath = "/Account/SignIn";
options.LogoutPath = "/Account/SignOut";
options.Cookie.SecurePolicy = CookieSecurePolicy.Always;
options.Events = new CookieAuthenticationEvents
{
OnRedirectToLogin = OnRedirectToLogin
};
});
and the OnAuthorizationCodeReceived
looks like this :
private async Task OnAuthorizationCodeReceived(Microsoft.AspNetCore.Authentication.JwtBearer.TokenValidatedContext ctx)
{
await Task.Run(async () =>
{
var oidClaim = ctx.Principal.Claims.FirstOrDefault(c => c.Type == "http://schemas.microsoft.com/identity/claims/objectidentifier");
if (!string.IsNullOrWhiteSpace(oidClaim?.Value))
{
var users = aadClient.Users;
var pagedCollection = await this.aadClient.Users.GetByObjectId(oidClaim.Value).MemberOf.ExecuteAsync();
do
{
var directoryObjects = pagedCollection.CurrentPage.ToList();
foreach (var directoryObject in directoryObjects)
{
var group = directoryObject as Microsoft.Azure.ActiveDirectory.GraphClient.Group;
if (group != null)
{
((ClaimsIdentity)ctx.Principal.Identity).AddClaim(new Claim(ClaimTypes.Role, group.DisplayName, ClaimValueTypes.String));
}
}
pagedCollection = pagedCollection.MorePagesAvailable ? await pagedCollection.GetNextPageAsync() : null;
}
while (pagedCollection != null);
}
});
}
I'm having a failure on the following line :
var pagedCollection = await
this.aadClient.Users.GetByObjectId(oidClaim.Value).MemberOf.ExecuteAsync();
the exception is System.PlatformNotSupportedException: Secure binary serialization is not supported on this platform.
I'm guessing that this is a restriction of asp net core but I cannot figure how to setup a workaround for this.
Thanks for any help !