本主題將說明 ASP.NET 應用程式如何使用表單驗證,讓使用者透過輕量型目錄存取協定 (LDAP) 對 Active Directory 進行驗證。使用者經過驗證並重新導向後,您可以使用 Global.asax 檔案的 Application_AuthenticateRequest 方法,將 GenericPrincipal 物件儲存在整個要求流程皆須使用的 HttpContext.User 屬性中。
建立新的 ASP.NET Web 應用程式
-
啟動 Microsoft Visual Studio .NET。
-
在 [檔案] 功能表上,指向 [新增],然後按一下 [專案]。
-
按一下 [專案類型] 下的 [Visual C# 專案],再按一下 [範本] 下的 [ASP.NET Web 應用程式]。
-
在 [名稱] 方塊中輸入 FormsAuthAd。
-
若要使用本機伺服器,請保留 [伺服器] 方塊中預設的 http://localhost。否則,請在伺服器中加入路徑。按一下 [確定]。
-
在 [方案總管] 中的 [參考] 節點上按一下滑鼠右鍵,再按一下 [加入參考]。
-
在 [加入參考] 對話方塊中的 [.NET] 索引標籤上按一下 System.DirectoryServices.dll,再按一下 [選取],然後按一下 [確定]。
加入 System.DirectoryServices 驗證程式碼
-
在 [方案總管] 中,以滑鼠右鍵按一下專案節點,指向 [加入],然後按一下 [加入新項目]。
-
按一下 [範本] 下的 [類別]。
-
在 [名稱] 方塊中鍵入 LdapAuthentication.cs,然後按一下 [開啟]。
-
將 LdapAuthentication.cs 檔案中現有的程式碼取代為下列程式碼:
C#using System; using System.Text; using System.Collections; using System.DirectoryServices; namespace FormsAuth { public class LdapAuthentication { private string _path; private string _filterAttribute; public LdapAuthentication(string path) { _path = path; } public bool IsAuthenticated(string domain, string username, string pwd) { string domainAndUsername = domain + @"/" + username; DirectoryEntry entry = new DirectoryEntry(_path, domainAndUsername, pwd); try { //Bind to the native AdsObject to force authentication. object obj = entry.NativeObject; DirectorySearcher search = new DirectorySearcher(entry); search.Filter = "(SAMAccountName=" + username + ")"; search.PropertiesToLoad.Add("cn"); SearchResult result = search.FindOne(); if(null == result) { return false; } //Update the new path to the user in the directory. _path = result.Path; _filterAttribute = (string)result.Properties["cn"][0]; } catch (Exception ex) { throw new Exception("Error authenticating user. " + ex.Message); } return true; } public string GetGroups() { DirectorySearcher search = new DirectorySearcher(_path); search.Filter = "(cn=" + _filterAttribute + ")"; search.PropertiesToLoad.Add("memberOf"); StringBuilder groupNames = new StringBuilder(); try { SearchResult result = search.FindOne(); int propertyCount = result.Properties["memberOf"].Count; string dn; int equalsIndex, commaIndex; for(int propertyCounter = 0; propertyCounter < propertyCount; propertyCounter&