Asp.Net基於forms的驗證機制,記錄一下…

來源:互聯網
上載者:User

最近在看asp.net forum,對其中的驗證機制看得模模糊糊,看完構建安全的 ASP.NET 應用程式中的表單身分識別驗證部分,思路就很清晰了,稍做了點記錄,以便查閱:

構建基於forms的驗證機制過程如下:

1,設定IIS為可匿名訪問和asp.net web.config中設定為form驗證

2,檢索資料存放區驗證使用者,並檢索角色(如果不是基於角色可不用)

3,使用FormsAuthenticationTicket建立一個Cookie並回傳到用戶端,並儲存

  角色到票中,如:

  FormsAuthentication.SetAuthCookie(Username,true | false)

  cookies儲存時間:

  HttpContext.Current.Response.Cookies[FormsAuthentication.FormsCookieName].Expires=DateTime.Now.AddDays(1)

  如果需要儲存角色,採用:

 FormsAuthenticationTicket authTicket = new

 FormsAuthenticationTicket(

            1, // version

            txtUserName.Text, // user name

            DateTime.Now, // creation

            DateTime.Now.AddMinutes(20),// Expiration

            false, // Persistent

            roles ); // User data

  roles是一個角色字串數組

  string encryptedTicket = FormsAuthentication.Encrypt(authTicket); //加密

  存入Cookie

  HttpCookie authCookie =

  new HttpCookie(FormsAuthentication.FormsCookieName,

  encryptedTicket);

  Response.Cookies.Add(authCookie);

4,在Application_AuthenticateRequest事件中處理常式中(Global.asax)中,使用

  票建立IPrincipal對象並存在HttpContext.User中

  代碼:

  HttpCookie authCookie = Context.Request.Cookies[FormsAuthentication.FormsCookieName];

  FormsAuthenticationTicket authTicket = FormsAuthentication.Decrypt(authCookie.Value);//解密

  string[] roles = authTicket.UserData.Split(new char[]{';'});//根據存入時的格式分解,;或|....

  Context.User = new GenericPrincipal(Context.User.Identity, Roles);//存在HttpContext.User中

5,需要對某些頁面進行角色控制,有兩種方法:

 5.1,web.config中加

    <location path="EditPost.aspx">

 <system.web>

  <authorization>

                        <allow roles="RoleName" />

   <deny users="?" />

  </authorization>

 </system.web>

    </location>

 5.2,把只能是某種角色訪問的檔案放在同一目錄下,在此目錄下添加一個web.config

   <configuration>

     <system.web>

 <authorization>

           <allow roles="RoleName" />

    <deny users="*" />

 </authorization>

     </system.web>

   </configuration>

  說明:子目錄的web.config設定優先於父目錄的web.config設定

這裡有一篇更全面的總結

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.