日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > C# >内容正文

C#

如何验证 Active Directory 使用表单身份验证和 Visual C#.NET

發布時間:2025/5/22 C# 19 豆豆
生活随笔 收集整理的這篇文章主要介紹了 如何验证 Active Directory 使用表单身份验证和 Visual C#.NET 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
本文引用下面的 Microsoft.NET 框架類庫名稱空間:
  • System.Text
  • System.DirectoryServices
  • System.Security.Principal
  • System.Web.Security
本分步指南演示如何將 ASP.NET 應用程序可以使用 Forms 身份驗證允許用戶使用輕型目錄訪問協議 (LDAP) 身份驗證 Active Directory。 用戶身份驗證中,并重定向之后,您可以 Application _ AuthenticateRequest 方法用于 Global.asax 文件的整個請求過程流 HttpContext.User 屬性存儲 GenericPrincipal 對象。

在 Visual C#.NET 創建 ASP.NET Web 應用程序請按照下列步驟創建名為 FormsAuthAd 在 Visual C#.NET 中的一個新 ASP.NET Web 應用程序:
  • 啟動 Microsoft Visual Studio.NET。
  • 文件 菜單上指向 新建 ,然后單擊 項目
  • 單擊 項目類型 下的 Visual C# 項目 ,然后單擊 模板 下的 ASP.NET Web 應用程序
  • 位置 框中將 WebApplication 1 替換為 FormsAuthAd 。
  • 單擊 確定
  • 右擊解決方案資源管理器 引用 節點,然后單擊 添加引用
  • 添加引用 對話框 .NET 選項卡中,單擊 System.DirectoryServices.dll ,單擊 選擇 ,然后單擊 確定
  • 編寫身份驗證代碼請按照下列步驟創建新的類文件名為 LdapAuthentication.cs:
  • 在解決方案資源管理器右鍵單擊該項目節點,指向 添加 ,然后單擊 添加新項
  • 單擊 模板 下的
  • 名稱 框中鍵入 LdapAuthentication.cs ,然后單擊了此操作的 打開
  • LdapAuthentication.cs 文件中的將現有代碼替換為下面的代碼
  • ?

    Code
    ?1using?System;
    ?2using?System.Text;
    ?3using?System.Collections;
    ?4using?System.DirectoryServices;
    ?5
    ?6namespace?FormsAuth
    ?7{????
    ?8??public?class?LdapAuthentication
    ?9??{
    10????private?String?_path;
    11????private?String?_filterAttribute;
    12
    13????public?LdapAuthentication(String?path)
    14????{
    15??????_path?=?path;
    16????}

    17????????
    18????public?bool?IsAuthenticated(String?domain,?String?username,?String?pwd)
    19????{
    20??????String?domainAndUsername?=?domain?+?@"\"?+?username;
    21??????DirectoryEntry?entry?=?new?DirectoryEntry(_path,?domainAndUsername,?pwd);
    22????????????
    23??????try
    24??????{????//Bind?to?the?native?AdsObject?to?force?authentication.????????????
    25?????????Object?obj?=?entry.NativeObject;
    26
    27????DirectorySearcher?search?=?new?DirectorySearcher(entry);
    28
    29????search.Filter?=?"(SAMAccountName="?+?username?+?")";
    30????search.PropertiesToLoad.Add("cn");
    31????SearchResult?result?=?search.FindOne();
    32
    33????if(null?==?result)
    34????{
    35????????return?false;
    36????}

    37
    38????//Update?the?new?path?to?the?user?in?the?directory.
    39????_path?=?result.Path;
    40????_filterAttribute?=?(String)result.Properties["cn"][0];
    41??????}

    42??????catch?(Exception?ex)
    43??????{
    44????????throw?new?Exception("Error?authenticating?user.?"?+?ex.Message);
    45??????}

    46
    47????return?true;
    48?????}

    49
    50?????public?String?GetGroups()
    51?????{
    52???????DirectorySearcher?search?=?new?DirectorySearcher(_path);
    53???????search.Filter?=?"(cn="?+?_filterAttribute?+?")";
    54???????search.PropertiesToLoad.Add("memberOf");
    55???????StringBuilder?groupNames?=?new?StringBuilder();
    56
    57???????try
    58???????{
    59?????????SearchResult?result?=?search.FindOne();
    60
    61?????int?propertyCount?=?result.Properties["memberOf"].Count;
    62
    63????????String?dn;
    64?????int?equalsIndex,?commaIndex;
    65????????????????
    66?????for(int?propertyCounter?=?0;?propertyCounter?<?propertyCount;?propertyCounter++)
    67?????{
    68???????dn?=?(String)result.Properties["memberOf"][propertyCounter];
    69
    70???????????equalsIndex?=?dn.IndexOf("=",?1);
    71???????commaIndex?=?dn.IndexOf(",",?1);
    72???????if(-1?==?equalsIndex)
    73???????{
    74?????????return?null;
    75????????????}

    76
    77???????????groupNames.Append(dn.Substring((equalsIndex?+?1),?(commaIndex?-?equalsIndex)?-?1));
    78???????groupNames.Append("|");
    79
    80?????????}

    81???????}

    82???????catch(Exception?ex)
    83???????{
    84?????????throw?new?Exception("Error?obtaining?group?names.?"?+?ex.Message);
    85???????}
    ????????????
    86???????return?groupNames.ToString();
    87?????}

    88???}

    89}

    90

    ?


    身份驗證代碼接受域、 用戶名、 一個的密碼和 Active Directory 中樹的路徑。 此代碼使用 LDAP 目錄提供程序。

    Logon.aspx 頁中的代碼調用 LdapAuthentication.IsAuthenticated 方法,并從用戶收集的憑據中傳遞。 DirectoryEntry 對象則,創建路徑目錄樹、 該用戶名和密碼。 在用戶名必須以"domain\username"格式。 DirectoryEntry 對象然后嘗試通過獲取 NativeObject 屬性強制 AdsObject 綁定。 如果成功,用戶的 CN 屬性獲取通過創建一個 DirectorySearcher 對象以及篩選 SAMAccountName 。 對用戶進行身份驗證后,則該 IsAuthenticated 方法返回 True

    要獲取用戶所屬的組的列表,此代碼將調用 LdapAuthentication.GetGroups 方法。 LdapAuthentication.GetGroups 方法獲取用戶所屬通過創建一個 DirectorySearcher 對象以及根據 memberOf 屬性進行篩選的安全組和通訊組的列表。 此方法返回由管道 (|) 分隔組的列表。

    請注意 LdapAuthentication.GetGroups 方法操縱和截斷字符串。 這減少了身份驗證 Cookie 中存儲的字符串的長度。 如果字符串未被截斷,每個組的格式顯示如下。

    CN=...,...,DC=domain,DC=com

    這可以創建一個很長的字符串。 如果此字符串的長度大于 cookie 的長度,瀏覽器可能不接受該身份驗證 Cookie,并您將被重定向到登錄頁。 但是,如果您處于多域環境時,可能不得不保留域名稱與組名稱,因為不同的域中的組可以有相同的組名稱。 您需要保留域名稱來彼此區分一個組。

    大多數瀏覽器支持的最多為 4096 字節的 Cookie。 如果該字符串可能可能會超出 Cookie 的長度,可能要在 ASP.NET 緩存對象或數據庫中存儲組信息。 或者,可能要加密組信息,并將此信息存儲在隱藏的窗體字段。

    編寫 Global.asax 代碼Global.asax 文件中的該代碼步指南提供了的 Application _ AuthenticateRequest 事件處理程序。 此事件處理程序從 Context.Request.Cookies 集合中檢索身份驗證 Cookie,以解密該 cookie,并檢索 FormsAuthenticationTicket.UserData 屬性中存儲組的列表。 這些組顯示在 Logon.aspx 頁中創建的管道分隔列表中。

    代碼分析字符串數組創建 GenericPrincipal 對象中的該字符串。 創建 GenericPrincipal 對象后,此對象將被置于 HttpContext.User 屬性。
  • 在解決方案資源管理器右鍵單擊 Global.asax ,然后單擊 查看代碼
  • 代碼的-隱藏 Global.asax.cs 文件頂部添加以下代碼: using System.Web.Security;using System.Security.Principal;
  • Application _ AuthenticateRequest 替換為下面的代碼的現有空事件處理程序
  • ?

    Code
    ?1void?Application_AuthenticateRequest(Object?sender,?EventArgs?e)
    ?2{
    ?3??String?cookieName?=?FormsAuthentication.FormsCookieName;
    ?4??HttpCookie?authCookie?=?Context.Request.Cookies[cookieName];
    ?5
    ?6??if(null?==?authCookie)
    ?7??{//There?is?no?authentication?cookie.
    ?8????return;
    ?9??}
    ????
    10????????
    11??FormsAuthenticationTicket?authTicket?=?null;
    12????
    13??try
    14??{
    15????authTicket?=?FormsAuthentication.Decrypt(authCookie.Value);
    16??}

    17??catch(Exception?ex)
    18??{
    19????//Write?the?exception?to?the?Event?Log.
    20????return;
    21??}

    22????
    23??if(null?==?authTicket)
    24??{//Cookie?failed?to?decrypt.
    25????return;????????
    26??}
    ????????
    27????
    28??//When?the?ticket?was?created,?the?UserData?property?was?assigned?a
    29??//pipe-delimited?string?of?group?names.
    30??String[]?groups?=?authTicket.UserData.Split(new?char[]{'|'});
    31
    32??//Create?an?Identity.
    33??GenericIdentity?id?=?new?GenericIdentity(authTicket.Name,?"LdapAuthentication");
    34????
    35??//This?principal?flows?throughout?the?request.
    36??GenericPrincipal?principal?=?new?GenericPrincipal(id,?groups);
    37
    38??Context.User?=?principal;
    39????
    40}

    ?

  • 修改 Web.config 文件在此部分中,您配置在 <forms><authentication><authorization>在 Web.config 文件中的元素。 用這些的更改只有經過身份驗證的用戶可以訪問應用程序,,并且未經身份驗證的請求重定向到 Logon.aspx 頁。 您可以修改此配置為允許僅特定用戶和組訪問應用程序。

    Web.config 文件中現有代碼替換為下面的代碼中。
    Code
    ?1<?xml?version="1.0"?encoding="utf-8"??>
    ?2<configuration>????
    ?3??<system.web>
    ?4????<authentication?mode="Forms">
    ?5??????<forms?loginUrl="logon.aspx"?name="adAuthCookie"?timeout="10"?path="/"?>
    ?6??????</forms>
    ?7????</authentication>????
    ?8????<authorization>????
    ?9??????<deny?users="?"?/>
    10??????<allow?users="*"?/>
    11????</authorization>????
    12????<identity?impersonate="true"?/>
    13??</system.web>
    14</configuration>

    請注意 配置元素。 這將導致 ASP.NET 模擬配置為匿名帳戶從 Microsoft Internet Information Services (IIS) 的帳戶。 因這種配置在配置的帳戶的安全上下文中運行此應用程序的所有請求。 用戶提供在 Active 的 Directory 身份驗證的憑據,但訪問 Active Directory 的帳戶是配置的帳戶。

    為匿名身份驗證配置 IIS要配置 IIS 為匿名身份驗證,請執行下列步驟:
  • IIS 中, 展開計算機節點,您的服務器,展開 網站 ,展開 默認網站 ,右鍵單擊 FormsAuthAd ,然后單擊 屬性 。
  • 單擊 目錄安全選項卡 中,然后單擊在 匿名訪問和身份驗證控制 下的 編輯 。
  • 請應用程序的匿名帳戶具有 Active Directory 的權限的帳戶。
  • 單擊以清除允許 IIS 控制密碼復選框。
  • 在的身份驗證訪問 ” 部分取消選中的集成的 Windows 身份驗證 ” 復選框。
  • 單擊確定。
  • 單擊應用
  • 默認 IUSR _ computername 帳戶沒有 Active Directory 的權限。

    創建 Logon.aspx 頁請按照下列步驟創建名為 Logon.aspx 的新 ASP.NET Web 窗體:
  • 在解決方案資源管理器右鍵單擊該項目節點,指向 添加 ,然后單擊 添加 Web 窗體
  • 名稱 框中鍵入 Logon.aspx ,,然后單擊了此操作的 打開
  • 在解決方案資源管理器右鍵單擊 Logon.aspx ,然后單擊 視圖設計器
  • 單擊 HTML 選項卡在設計器中。
  • Replace the existing code with the following code. Code
    ?1<%@?Page?language="c#"?AutoEventWireup="true"?%>
    ?2<%@?Import?Namespace="FormsAuth"?%>
    ?3<html>
    ?4??<body>????
    ?5????<form?id="Login"?method="post"?runat="server">
    ?6??????<asp:Label?ID="Label1"?Runat=server?>Domain:</asp:Label>
    ?7??????<asp:TextBox?ID="txtDomain"?Runat=server?></asp:TextBox><br>????
    ?8??????<asp:Label?ID="Label2"?Runat=server?>Username:</asp:Label>
    ?9??????<asp:TextBox?ID=txtUsername?Runat=server?></asp:TextBox><br>
    10??????<asp:Label?ID="Label3"?Runat=server?>Password:</asp:Label>
    11??????<asp:TextBox?ID="txtPassword"?Runat=server?TextMode=Password></asp:TextBox><br>
    12??????<asp:Button?ID="btnLogin"?Runat=server?Text="Login"?OnClick="Login_Click"></asp:Button><br>
    13??????<asp:Label?ID="errorLabel"?Runat=server?ForeColor=#ff3300></asp:Label><br>
    14??????<asp:CheckBox?ID=chkPersist?Runat=server?Text="Persist?Cookie"?/>
    15????</form>????
    16??</body>
    17</html>
    18<script?runat=server>
    19void?Login_Click(Object?sender,?EventArgs?e)
    20{
    21??String?adPath?=?"LDAP://corp.com";?//Fully-qualified?Domain?Name
    22??LdapAuthentication?adAuth?=?new?LdapAuthentication(adPath);
    23??try
    24??{
    25????if(true?==?adAuth.IsAuthenticated(txtDomain.Text,?txtUsername.Text,?txtPassword.Text))
    26????{
    27??????String?groups?=?adAuth.GetGroups();
    28
    29??????//Create?the?ticket,?and?add?the?groups.
    30??????bool?isCookiePersistent?=?chkPersist.Checked;
    31??????FormsAuthenticationTicket?authTicket?=?new?FormsAuthenticationTicket(1,??txtUsername.Text,
    32????DateTime.Now,?DateTime.Now.AddMinutes(60),?isCookiePersistent,?groups);
    33????
    34??????//Encrypt?the?ticket.
    35??????String?encryptedTicket?=?FormsAuthentication.Encrypt(authTicket);
    36????????
    37??????//Create?a?cookie,?and?then?add?the?encrypted?ticket?to?the?cookie?as?data.
    38??????HttpCookie?authCookie?=?new?HttpCookie(FormsAuthentication.FormsCookieName,?encryptedTicket);
    39
    40??????if(true?==?isCookiePersistent)
    41????authCookie.Expires?=?authTicket.Expiration;
    42????????????????
    43??????//Add?the?cookie?to?the?outgoing?cookies?collection.
    44??????Response.Cookies.Add(authCookie);????????
    45
    46??????//You?can?redirect?now.
    47??????Response.Redirect(FormsAuthentication.GetRedirectUrl(txtUsername.Text,?false));
    48????}

    49????else
    50????{
    51??????errorLabel.Text?=?"Authentication?did?not?succeed.?Check?user?name?and?password.";
    52????}

    53??}

    54??catch(Exception?ex)
    55??{
    56????errorLabel.Text?=?"Error?authenticating.?"?+?ex.Message;
    57??}

    58}

    59
    </script>
  • 修改路徑指向您的 LDAP 目錄服務器 Logon.aspx 頁中。
  • Logon.aspx 頁是從用戶和調用方法收集信息, LdapAuthentication 類一頁。 代碼對用戶進行身份驗證,并獲取組的列表之后,代碼創建一個 FormsAuthenticationTicket 對象,加密票證、 添加加密的票證一個 Cookie,將 Cookie 添加到 HttpResponse.Cookies 集合中,然后將請求重定向到最初請求的 URL。

    修改 WebForm 1.aspx 頁WebForm 1.aspx 頁是原來請求的頁。 當用戶請求該頁時, 將請求重定向到在 Logon.aspx 頁。 該請求進行身份驗證后,請求將被重定向到 WebForm 1.aspx 頁中。
  • 在解決方案資源管理器右鍵單擊 WebForm 1.aspx ,然后單擊 視圖設計器
  • 單擊 HTML 選項卡在設計器中。
  • 現有代碼替換為以下 code.?
    Code
    ?1<%@?Page?language="c#"?AutoEventWireup="true"?%>
    ?2<%@?Import?Namespace="System.Security.Principal"?%>
    ?3<html>
    ?4??<body>????
    ?5????<form?id="Form1"?method="post"?runat="server">
    ?6??????<asp:Label?ID="lblName"?Runat=server?/><br>
    ?7??????<asp:Label?ID="lblAuthType"?Runat=server?/>
    ?8????</form>????
    ?9??</body>
    10</html>
    11<script?runat=server>
    12void?Page_Load(Object?sender,?EventArgs?e)
    13{
    14??lblName.Text?=?"Hello?"?+?Context.User.Identity.Name?+?".";
    15??lblAuthType.Text?=?"You?were?authenticated?using?"?+???Context.User.Identity.AuthenticationType?+?".";
    16}

    17
    </script>
  • 保存所有的文件,并再編譯該項目。
  • 請求 WebForm 1.aspx 頁。 請注意您將被重定向到 Logon.aspx。
  • 鍵入登錄的憑據,然后單擊 提交 。 當您將被重定向到 WebForm 1.aspx 時, 請注意您的用戶名出現和該 LdapAuthentication 是身份驗證類型為 Context.User.AuthenticationType 屬性。
  • 請注意 Microsoft 建議您使用安全套接字層 (SSL) 加密使用 Forms 身份驗證時。 這是因為用戶標識基于該身份驗證 cookie,并且此應用程序上的 SSL 加密防止任何人破壞身份驗證 Cookie 和任何其他正在傳輸的重要信息。

    轉載于:https://www.cnblogs.com/allenlizq/archive/2009/02/20/1395200.html

    總結

    以上是生活随笔為你收集整理的如何验证 Active Directory 使用表单身份验证和 Visual C#.NET的全部內容,希望文章能夠幫你解決所遇到的問題。

    如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。