2010-10-21 52 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

相關問題