如何从@context.User 获取用户的名字或姓氏?

ca9*_*3d9 4 active-directory asp.net-authorization razor asp.net-core blazor

我使用 Windows 身份验证创建了一个服务器端 Blazor 应用程序。它创建了以下文件。

登录Display.razor

<AuthorizeView>
    Hello, @context.User.Identity.Name!
</AuthorizeView>
Run Code Online (Sandbox Code Playgroud)

但是,它显示“域\用户名”。它是一种显示用户名字的方法吗?

我试图打印所有的索赔类型。

@foreach(var c in context.User.Claims)
{
    <p>@c.Value @c.Type</p>
}
Run Code Online (Sandbox Code Playgroud)

但是,只有一种类型带有名称。(价值为DOMAIN\username

http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name
Run Code Online (Sandbox Code Playgroud)

小智 5

您还可以使用目录服务(使用 NuGet 安装),如下所示使用它。

_Imports.razor

@using System.DirectoryServices.AccountManagement
Run Code Online (Sandbox Code Playgroud)

登录Display.razor

<AuthorizeView>
    @{
        var pcontext = new PrincipalContext(ContextType.Domain, "XYZ.net", "DC=XYZ,DC=net");
        var principal = UserPrincipal.FindByIdentity(pcontext, context.User.Identity.Name);
    }    
    Hello, @principal.GivenName @principal.Surname!
</AuthorizeView>
Run Code Online (Sandbox Code Playgroud)


Gab*_*uci 4

您必须去 AD 获取该信息。但在 ASP.NET Core 中连接到 AD 并不简单。

如果您只想在 Windows 服务器上运行它,那么您可以Microsoft.Windows.Compatibility从 NuGet 安装,并DirectoryEntry使用其 SID 直接绑定到对象。SID 可在context.User.Identity.User.Value.

<AuthorizeView>
@{
    var identity = (WindowsIdentity) context.User.Identity;
    var user = new DirectoryEntry($"LDAP://<SID={identity.User.Value}>");

    //Add any other attributes you want to read to this list
    user.RefreshCache(new [] { "givenName" });
}
    Hello, @user.Properties["givenName"].Value!
</AuthorizeView>
Run Code Online (Sandbox Code Playgroud)

您可能感兴趣的其他属性:

  • sn: 姓
  • displayName:例如,他们的姓名在 Outlook 中的显示方式。通常这是“最后,第一个”