2010-10-21 56 views
10

我正在使用windows身份验证并访问用户名。如何在asp.net中获取用户详细信息Windows身份验证

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

但我想获得其他细节,如用户全名和EmailID。

+0

是否使用memebership提供商在应用程序中添加自己的属性等? – Restuta 2010-10-21 09:59:04

+0

不,我的应用程序。在Intranet上使用Windows身份验证。 – 2010-10-21 10:02:23

回答

14

既然你是Windows网络上,那么你需要查询Active Directory来搜索用户,然后得到它的属性,如电子邮件

这里是给定一个窗口验证网络上的IIdentity一个例子功能DisplayUser,找到用户的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]); 
     } 
    } 
} 

给出了这样的: alt text

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

+1

Jeevan。这个例子不适合你吗? – 2010-10-21 10:42:57

+0

谢谢,但...我使用Windows身份验证,所以我的目的是:现在有一个USL“http://ipAddress/myApp/home.aspx”现在当使用在内部网上打开它,然后在屏幕上,我们将看到他的登录姓名,全名和emailid。他不会做任何其他事情。现在来看看我们的代码...我们将如何设置“myPassword”。 – 2010-10-21 10:45:09

+0

编辑了答案,使其更简单。现在好吗? – 2010-10-21 11:04:24

-2

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

+0

我想你还没有读过我的问题。我需要全名和emailid。我们无法通过WindowsIdentity获取这些详细信息。 – 2010-10-21 10:05:13

-1

您可以通过从IIdentity覆盖定义MyCustomIdentity

相关问题