ASP.NET Forms 身份驗證

ASP.NET Forms 身份驗證

在開發過程當中,咱們須要作的事情包括:

1. 在 web.config 中設置 Forms 身份驗證相關參數。
2. 建立登陸頁。

登陸頁中的操做包括:

1. 驗證用戶名和密碼是否正確。
2. 建立身份驗證票證對象。
3. 將身份驗證票證對象加密成字符串,寫入 Cookies。
4. 重定向到原始請求 URL。

1. 簡單演示

web.config
<?xml version="1.0"?>
<configuration>
  <system.web>
    <compilation debug="true"/>
    <authentication mode="Forms">
      <forms loginUrl="~/logon.aspx" name="MyAuthForm">
        <credentials passwordFormat="Clear">
          <user name="username" password="password"/>
        </credentials>
      </forms>
    </authentication>
    <authorization>
      <deny users="?"/>
    </authorization>
  </system.web>
</configuration>

logon.aspx
<%@ Page Language="C#" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<script runat="server">
  protected void Button1_Click(object sender, EventArgs e)
  {
    if (FormsAuthentication.Authenticate(this.txtUsername.Text, this.txtPassword.Text))
      FormsAuthentication.RedirectFromLoginPage(this.txtUsername.Text, true);
    else
      Response.Write("用戶名或密碼錯誤!");
  }
</script>

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
 <title>登陸頁</title>
</head>
<body>
 <form id="form1" runat="server">
 <div>
    Username: <asp:TextBox ID="txtUsername" runat="server" Width="100px" Text="username"></asp:TextBox><br />
    Password: <asp:TextBox ID="txtPassword" runat="server" Width="100px" Text="password"></asp:TextBox><br />
    <asp:Button ID="Button1" runat="server" Text="Sign In" OnClick="Button1_Click" />
 </div>
 </form>
</body>
</html>

2. Forms 驗證參數

若是隻是某些子目錄中的頁面訪問請求須要進行身份驗證,那麼能夠修改一下根路徑下的 web.config。

web.config
<?xml version="1.0"?>
<configuration>
  <system.web>
    <compilation debug="true"/>
    <authentication mode="Forms">
      <forms loginUrl="~/logon.aspx" name="MyAuthForm">
        <credentials passwordFormat="Clear">
          <user name="username" password="password"/>
        </credentials>
      </forms>
    </authentication>
    <authorization>
      <allow users="*"/>
    </authorization>
  </system.web>
</configuration>

而後在須要進行身份驗證的子目錄中建立一個新的 web.config。
<?xml version="1.0"?>
<configuration>
  <system.web>
    <authorization>
      <deny users="?"/>
    </authorization>
  </system.web>
</configuration>

咱們還能夠在根路徑下的 web.config 中指定相關參數來控制身份驗證模式。
cookieless
  定義是否使用 Cookie 以及 Cookie 的行爲。
  .UseCookies
    指定不管在什麼設備上都始終使用 Cookie。
  .UseUri
    指定從不使用 Cookie。
  .AutoDetect
    若是設備配置文件支持 Cookie,則指定使用 Cookie;不然不使用 Cookie。
  .UseDeviceProfile
    若是瀏覽器支持 Cookie,則指定使用 Cookie;不然不使用 Cookie。
    對於支持 Cookie 的設備,不嘗試經過探測來肯定是否已啓用 Cookie 支持。
 
defaultUrl
  定義在身份驗證以後用於重定向的默認 URL。 默認值爲 "default.aspx"。
  當咱們直接打開登陸頁進行登陸後,該屬性就很重要了。

loginUrl
  指定若是找不到任何有效的身份驗證 Cookie,將請求重定向到的用於登陸的 URL。默認值爲 login.aspx。
 
name
  指定要用於身份驗證的 HTTP Cookie。若是正在一臺服務器上運行多個應用程序而且每一個應用程序都須要
  惟一的 Cookie,則必須在每一個應用程序的 Web.config 文件中配置 Cookie 名稱。默認值爲 ".ASPXAUTH"。
 
path
  爲應用程序發出的 Cookie 指定路徑。
  默認值是斜槓 (/),這是由於大多數瀏覽器是區分大小寫的,若是路徑大小寫不匹配,瀏覽器不會送回 Cookie。
 
timeout
  指定 Cookie 過時前逝去的時間(以整數分鐘爲單位)。持久性 Cookie 不超時。默認值爲 "30"(30 分鐘)。

更詳細信息,請參考 MSDN 文檔。
ms-help://MS.MSDNQTR.v80.chs/MS.MSDN.v80/MS.NETDEVFX.v20.chs/dv_ASPNETgenref/html/8163b8b5-ea6c-46c8-b5a9-c4c3de31c0b3.htm
<?xml version="1.0"?>
<configuration>
  <system.web>
    <compilation debug="true"/>
    <authentication mode="Forms">
      <forms loginUrl="~/logon.aspx" name="MyForm" defaultUrl="index.aspx" timeout="10">
        <credentials passwordFormat="Clear">
          <user name="username" password="password"/>
        </credentials>
      </forms>
    </authentication>
    <authorization>
      <allow users="*"/>
    </authorization>
  </system.web>
</configuration>

3. 驗證方法

咱們可使用下面 4 種方法中的一種進行票證寫入和重定向操做,其實前 3 種只不過是對第 4 種方法的封裝而已。推薦使用 一、4。注意後三種方法不支持cookieless="UseUri"。
// 1. 使用缺省身份驗證票證
FormsAuthentication.RedirectFromLoginPage("username", true);

// 2. 使用缺省身份驗證票證
FormsAuthentication.SetAuthCookie("username", false);
Response.Redirect(FormsAuthentication.GetRedirectUrl("username", false));

// 3. 使用缺省身份驗證票證
Response.Cookies.Add(FormsAuthentication.GetAuthCookie("username", false));
Response.Redirect(FormsAuthentication.GetRedirectUrl("username", false));

// 4. 使用自定義身份驗證票證
FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1, "username", DateTime.Now, DateTime.Now.AddMinutes(10), false, null);
Response.Cookies.Add(new HttpCookie(FormsAuthentication.FormsCookieName, FormsAuthentication.Encrypt(ticket)));
Response.Redirect(FormsAuthentication.GetRedirectUrl("username", false));

4. 自定義身份標識類型

MSDN 文檔告訴咱們,能夠在 Global.asax 中經過 Authenticate 事件使用自定義 Principal、Identity 替代 GenericPrincipal、FormsIdentity。由於 Authenticate 事件在 AuthenticateRequest 事件期間引起,所以咱們能夠在其餘模塊以前建立用戶身份標識對象(FormsAuthenticationEventArgs.User)。

ms-help://MS.MSDNQTR.v80.chs/MS.MSDN.v80/MS.NETDEVFX.v20.chs/cpref12/html/T_System_Web_Security_FormsAuthenticationEventHandler.htm
class MyPrincipal : System.Security.Principal.IPrincipal
{
  // ...
}

class MyIdentity : System.Security.Principal.IIdentity
{
  // ...
}
  
public void FormsAuthentication_OnAuthenticate(object sender, FormsAuthenticationEventArgs args)
{
  if (FormsAuthentication.CookiesSupported)
  {
    if (Request.Cookies[FormsAuthentication.FormsCookieName] != null)
    {
      try
      {
        FormsAuthenticationTicket ticket = FormsAuthentication.Decrypt(
          Request.Cookies[FormsAuthentication.FormsCookieName].Value);
 
        args.User = new MyPrincipal(new MyIdentity (ticket), new string[0]);
      }
      catch (Exception e)
      {
        // Decrypt method failed.
      }
    }
  }
  else
  {
    throw new HttpException("Cookieless Forms Authentication is not " +
      "supported for this application.");
  }

}

固然,還有另一種簡便的方法。
if (!(HttpContext.Current.User is MyPrincipal))
{
  HttpContext.Current.User = new MyPrincipal(new MyIdentity(ticket), roles);
}

只不過,你要找一個合適的時機而已。

5. FormsAuthentication

Authenticate
對照存儲在應用程序配置文件中的憑據來驗證用戶名和密碼。該方法只能驗證存儲在 web.config 中的用戶名和密碼信息,大多數時候咱們會用本身的驗證方法替代它。

Decrypt
解密從 Cookie 中獲取的加密字符串,建立 FormsAuthenticationTicket 對象。

Encrypt
加密 FormsAuthenticationTicket,返回加密後字符串。

GetRedirectUrl
返回致使重定向到登陸頁的原始請求 URL。GetRedirectUrl 方法返回查詢字符串中使用 ReturnURL 變量名指定的 URL。例如,在 URL http://www.contoso.com/login.aspx?ReturnUrl=caller.aspx 中,GetRedirectUrl 方法返回返回 caller.aspx。若是 ReturnURL 變量不存在,GetRedirectUrl 方法將返回 DefaultUrl 屬性中的 URL。

RedirectFromLoginPage
將通過身份驗證的用戶重定向回最初請求的 URL 或 DefaultUrl 。

RedirectToLoginPage
將瀏覽器重定向到登陸 URL。

RenewTicketIfOld
有條件地更新 FormsAuthenticationTicket 的發出日期和時間以及過時日期和時間。 注意該方法只是返回更新後的 FormsAuthenticationTicket 對象,並不會寫入 Cookies。

GetAuthCookie
爲給定的用戶名建立身份驗證 Cookie,並不添加到響應的 Cookie 集合或 URL。

SetAuthCookie
爲提供的用戶名建立一個身份驗證票證,並將其添加到響應的 Cookie 集合或 URL。

SignOut
從瀏覽器刪除 Forms 身份驗證票證。

6. 票證自定義數據應用 使用自定義票證時,咱們能夠添加一個 userData 參數。善加利用這個參數仍是能帶了一些意想不到的好處的,諸如存儲用戶 VIP 等級編號,所擁有的權限/角色集合等。固然 Cookie 和 URL 參數長度有限,這個自定義數據不能太長。
相關文章
相關標籤/搜索