【问题标题】:How to get user details in asp.net Windows Authentication如何在 asp.net Windows 身份验证中获取用户详细信息
【发布时间】:2010-10-21 09:50:39
【问题描述】:

我正在使用 windows 身份验证和访问用户名。

IIdentity winId = HttpContext.Current.User.Identity;
string name = winId.Name;

但我想获取其他详细信息,例如用户全名和电子邮件 ID。

【问题讨论】:

  • 您是否在您的应用程序中使用了会员资格提供商?
  • 不,我的应用程序。在 Intranet 上,所以使用 windows 身份验证。

标签: asp.net


【解决方案1】:

由于你在windows网络上,那么你需要查询活动目录来搜索用户,然后得到它的属性,比如电子邮件

这是一个示例函数 DisplayUser,它在 Windows 身份验证网络上给定 IIdentity,找到用户的 email

public static void Main() {
    DisplayUser(WindowsIdentity.GetCurrent());
    Console.ReadKey();    
}

public static void DisplayUser(IIdentity id) {    
    WindowsIdentity winId = id as WindowsIdentity;
    if (id == null) {
        Console.WriteLine("Identity is not a windows identity");
        return;
    }

    string userInQuestion = winId.Name.Split('\\')[1];
    string myDomain = winId.Name.Split('\\')[0]; // this is the domain that the user is in
     // the account that this program runs in should be authenticated in there                    
    DirectoryEntry entry = new DirectoryEntry("LDAP://" + myDomain);
    DirectorySearcher adSearcher = new DirectorySearcher(entry);

    adSearcher.SearchScope = SearchScope.Subtree;
    adSearcher.Filter = "(&(objectClass=user)(samaccountname=" + userInQuestion + "))";
    SearchResult userObject = adSearcher.FindOne();
    if (userObject != null) {
        string[] props = new string[] { "title", "mail" };
        foreach (string prop in props) {
            Console.WriteLine("{0} : {1}", prop, userObject.Properties[prop][0]);
        }
    }
}

给出了这个:

编辑:如果您收到“错误的用户/密码错误” 运行代码的帐户必须有权访问用户域。如果您在 asp.net 中运行代码,则 Web 应用程序必须在具有域访问凭据的应用程序池下运行。更多信息请见here

【讨论】:

  • 谢谢,但是...我正在使用 Windows 身份验证,所以我的目的是:现在有一个 usl "ipAddress/myApp/home.aspx" 当使用在内网打开它然后在屏幕上我们会看到他的登录名, 全名和emailid。他不会做任何其他事情。现在来到你的代码......我们将如何设置“myPassword”。
  • Alt+PrintScreen 将仅捕获选定的窗口,因此您不会在生成的屏幕截图中出现背景噪音
  • @Preet:在本地(bebug)中它工作正常,但在 iis 中它给出错误...System.DirectoryServices.DirectoryServicesCOMException:登录失败:未知用户名或密码错误。
【解决方案2】:

您可以通过覆盖IIdentity 来定义MyCustomIdentity 并添加您自己的属性等。

【讨论】:

    【解决方案3】:

    将其转换为特定的身份,例如WindowsIdentity

    【讨论】:

    • 我想你还没有阅读我的问题。我需要全名和emailid。我们无法通过 WindowsIdentity 获取这些详细信息。
    猜你喜欢
    • 1970-01-01
    • 2019-01-27
    • 2012-09-15
    • 1970-01-01
    • 1970-01-01
    • 2010-11-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多