【问题标题】:ClaimTypes.NameIdentifier returns always null in Blazor WebAssembly ASP.NET Core HostedClaimTypes.NameIdentifier 在 Blazor WebAssembly ASP.NET Core Hosted 中始终返回 null
【发布时间】:2020-10-29 10:56:25
【问题描述】:

我已经设置了一个Blazor WebAssembly ASP.NET Core hosted应用程序并将身份验证系统以及自定义AuthenticationProvider集成到客户端。在服务器端项目中,我在控制器中调用:

[HttpGet]
public async Task<ActionResult> GetObjects()
{
   var id = User.FindFirstValue(ClaimTypes.NameIdentifier); // <-- returns always null
}

id 变量总是返回 null。

用户来自aspnetcoreuser表(aspnetcore身份) 在表数据中,我可以看到,当我使用 SQLite 时,id 不为空,并且用户已成功添加到 aspnetuser 表中。

一些 SDK 版本:

.NET Core SDK 已安装: 3.1.301 .NET Core 运行时安装:Microsoft.AspNetCore.All 2.1.19 Microsoft.AspNetCore.App 2.1.19Microsoft.AspNetCore.App 3.1.5 Microsoft.NETCore.App 2.1.19 Microsoft.NETCore.App 3.1.5 Microsoft.WindowsDesktop.App 3.1.5

我还看到了一些解决方案,launchSettings.json 中的 "windowsAuthentication": true, "anonymousAuthentication": false, 可能会导致该问题,但通过更改它并没有为我解决。

这里有谁能帮帮我吗?

【问题讨论】:

    标签: c# asp.net-core blazor asp.net-authorization blazor-webassembly


    【解决方案1】:

    您需要在服务器应用程序上设置UserIdClaimType,方法是将此代码添加到Startup.ConfigureServices:

    services.Configure<IdentityOptions>(options => 
        options.ClaimsIdentity.UserIdClaimType = ClaimTypes.NameIdentifier);
    

    阅读更多here

    【讨论】:

    • 感谢您的回复!没错,缺少服务器依赖项,但现在我得到一个异常:System.NullReferenceException: "Object reference not set to an instance of an object."
    • 我注意到控制器内部的用户通常为空。我是否缺少任何依赖项注册?认为控制器默认可以访问用户而不集成任何httpcontext。
    • 什么是服务器应用程序设置?在客户端/服务器模型中,我们应该使用访问令牌来调用服务器应用程序中受保护的资源 API。并且服务器应用程序应该设置为读取令牌并获得授权 - 你能确认这是你所拥有的吗?
    • 感谢您的参考。帮助解决了我的 GetUserAsync(User) 返回 Null 的问题。必须将其设置为正确的 ClaimTypes。
    猜你喜欢
    • 2020-08-27
    • 1970-01-01
    • 2020-09-30
    • 1970-01-01
    • 2020-05-24
    • 2023-03-17
    • 2019-05-27
    • 2018-11-09
    • 1970-01-01
    相关资源
    最近更新 更多