mic*_*sot 6 azure-ad-graph-api azure-ad-b2c asp.net-core-webapi asp.net-core-2.0
我正在创建一个使用 azure AD B2C 进行身份验证的 asp net core 2 web api。我想使用 AD B2C 组将某些控制器的使用限制为管理员成员。
我已经明白,目前实现这一目标的唯一方法是访问图形 API 并将一些角色声明添加到用户的声明中。
但是我在启动时查询图形 api 时遇到了麻烦。
我的ConfigureService方法是这样的:
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
};
});
Run Code Online (Sandbox Code Playgroud)
和OnAuthorizationCodeReceived看起来像这样:
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);
}
});
}
Run Code Online (Sandbox Code Playgroud)
我在以下行失败:
var pagedCollection = await
this.aadClient.Users.GetByObjectId(oidClaim.Value).MemberOf.ExecuteAsync();
Run Code Online (Sandbox Code Playgroud)
例外是 System.PlatformNotSupportedException: Secure binary serialization is not supported on this platform.
我猜这是对 asp net core 的限制,但我无法弄清楚如何为此设置解决方法。
谢谢你的帮助 !
| 归档时间: |
|
| 查看次数: |
1257 次 |
| 最近记录: |