获取经过身份验证的用户的全名

时间:2021-02-10 15:30:31

标签: c# .net wcf

目标

我有一个使用 Windows 身份验证的 WCF 服务。我想确定连接的用户的全名。用户可以是域用户或本地用户。对于本地用户,可以在[计算机管理(本地)>本地用户和组>用户>[用户]>全名]中查看全名。

FindByIdentity 几乎成功

我可以使用 UserPrincipal.FindByIdentity() 来检索 UserPrincipal 对象,然后从 UserPrincipal.DisplayName 中获取它。 FindByIdentity 的第一个参数需要指定 ContextType,例如 Domain 或 Machine。

  • 使用 ContextType.Domain 和本地用户调用 FindByIdentity,会产生“指定的域不存在或无法联系”异常
  • 使用 ContextType.Machine 和域用户调用 FindByIdentity,生成没有填充 DisplayName 属性的 UserPrincipal

所以我想避免猜测。

问题

  • 如何获得已连接用户的全名?
  • 或者如何区分连接的用户是域用户还是本地用户?

目前的代码

string GetFullName()
{
    using (var ctx = new PrincipalContext(ContextType.Domain))
    {
        string userName = OperationContext.Current.ServiceSecurityContext.WindowsIdentity.Name;
        UserPrincipal u = UserPrincipal.FindByIdentity(ctx, userName);
        return u.DisplayName;
    }
}

2 个答案:

答案 0 :(得分:0)

您可以使用 Environment.UserDomainName 属性获取当前用户的域名。如果未加入域,则返回当前用户的主机名。

答案 1 :(得分:0)

我现在正在使用以下内容。如果有人有更好的想法,请发表您的答案

bool LocalUserConnected()
{
    string userName = OperationContext.Current.ServiceSecurityContext.WindowsIdentity.Name;
    return userName.StartsWith(Environment.MachineName + @"\");
}