【发布时间】:2020-08-21 21:21:57
【问题描述】:
我正在尝试在我正在构建的 Blazor WASM 应用程序上为我的身份平台切换到 Azure AD。我非常密切地关注来自 Microsoft 的 this documentation。
当我登录应用程序时,客户端应用程序能够显示登录用户的名称,该名称来自 AuthenticationState 对象。
但是,在服务器端,当我发送 HTTP 请求(例如发布评论)时,HttpContext.User.Claims 为空,并且我之前用于获取 userId 的以下行返回 null:
comment.UserId = HttpContext.User.FindFirstValue(ClaimTypes.NameIdentifier);
我为对声明/身份/Microsoft Graph 等方面的一些无知表示歉意,但我仍然不明白为什么用户/声明将是未知的,因为自从客户端应用程序能够访问此信息以来,至少在某个时间点可以访问此信息显示用户名...
我还查看了以下 StackOverflow/GitHub 帖子,但没有找到任何解决此问题的方法:
- Blazor with AzureAD Auth, Context.Identity.User.Name is null
- Out of box AAD B2C not grabbing user.identity.name
- User.Identity.Name empty when implementing Azure B2C in Blazor WebAssembly
为了能够在传入的 HTTP 请求中识别用户,我在这里缺少什么?
FWIW,这是我的 Startup.cs 类(发出了一些不相关的代码):
public void ConfigureServices(IServiceCollection services)
{
#region Azure Active Directory
services.AddAuthentication(AzureADDefaults.BearerAuthenticationScheme)
.AddAzureADBearer(options => {
Configuration.Bind("AzureAd", options);
}
);
#endregion
services.Configure<JwtBearerOptions>(
AzureADDefaults.JwtBearerAuthenticationScheme, options =>
{
options.TokenValidationParameters.NameClaimType = "name";
//options.TokenValidationParameters.NameClaimType = "preferred_username";
});
services.AddHttpContextAccessor();
services.AddControllersWithViews().AddNewtonsoftJson(x => x.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore);
services.AddRazorPages();
}
和配置():
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
app.UseHttpsRedirection();
app.UseBlazorFrameworkFiles();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapRazorPages();
endpoints.MapControllers();
endpoints.MapFallbackToFile("index.html");
});
}
【问题讨论】:
-
您是否创建了自定义用户工厂来处理角色和组声明?
-
我没有,但该设置文档中也没有将其列为要求。我找到了原因,客户端 ID 没有附加方案/协议,这似乎很奇怪,它有这种效果。这条特定的行在这里被称为:docs.microsoft.com/en-us/aspnet/core/blazor/security/…,但他们将其描述为“尝试任何一个”,我觉得这很奇怪。是否有自定义用户工厂的教程文档/概述来处理角色/组声明?我真的很难找到这个过程的概述。
标签: azure-active-directory asp.net-identity microsoft-graph-api blazor