FormsAuthentication FormsAuthentication FormsAuthentication FormsAuthentication Class

定義

管理 Web 應用程式的表單驗證服務。Manages forms-authentication services for Web applications. 這個類別無法被繼承。This class cannot be inherited.

public ref class FormsAuthentication sealed
public sealed class FormsAuthentication
type FormsAuthentication = class
Public NotInheritable Class FormsAuthentication
繼承
FormsAuthenticationFormsAuthenticationFormsAuthenticationFormsAuthentication

範例

下列程式碼範例會顯示為表單驗證使用 ASP.NET 成員資格提供者,並要求所有使用者都必須經過驗證的 ASP.NET 應用程式的 Web.config 檔案。The following code example shows the Web.config file for an ASP.NET application that uses the ASP.NET membership provider for forms authentication and requires all users to be authenticated.

<configuration>  
  <connectionStrings>  
    <add name="SqlServices" connectionString="Data Source=MySqlServer;Integrated Security=SSPI;Initial Catalog=aspnetdb;" />  
  </connectionStrings>  
  <system.web>  
    <membership defaultProvider="SqlProvider" userIsOnlineTimeWindow="20">  
      <providers>  
        <add name="SqlProvider"  
          type="System.Web.Security.SqlMembershipProvider"  
          connectionStringName="SqlServices"  
          enablePasswordRetrieval="false"  
          enablePasswordReset="true"  
          requiresQuestionAndAnswer="true"  
          passwordFormat="Hashed"  
          applicationName="/" />  
      </providers>  
    </membership>  
  </system.web>  
</configuration>  

下列程式碼範例示範使用表單驗證和 ASP.NET 成員資格的 ASP.NET 應用程式的登入頁面。The following code example shows the login page for an ASP.NET application that uses forms authentication and ASP.NET membership.

重要

此範例包含一個文字方塊,接受使用者輸入,也就是潛在的安全性威脅。This example contains a text box that accepts user input, which is a potential security threat. 根據預設,ASP.NET Web 網頁會驗證使用者輸入未包含指令碼或 HTML 項目。By default, ASP.NET Web pages validate that user input does not include script or HTML elements. 如需詳細資訊,請參閱 Script Exploits Overview (指令碼攻擊概觀)。For more information, see Script Exploits Overview.

<%@ Page Language="C#" %>
<%@ Import Namespace="System.Web.Security" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">

public void Login_OnClick(object sender, EventArgs args)
{
   if (Membership.ValidateUser(UsernameTextbox.Text, PasswordTextbox.Text))
      FormsAuthentication.RedirectFromLoginPage(UsernameTextbox.Text, NotPublicCheckBox.Checked);
   else
     Msg.Text = "Login failed. Please check your user name and password and try again.";
}


</script>

<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
  <title>Login</title>
</head>
<body>

<form id="form1" runat="server">
  <h3>Login</h3>

  <asp:Label id="Msg" ForeColor="maroon" runat="server" /><br />

  Username: <asp:Textbox id="UsernameTextbox" runat="server" /><br />
  Password: <asp:Textbox id="PasswordTextbox" runat="server" TextMode="Password" /><br />
 
  <asp:Button id="LoginButton" Text="Login" OnClick="Login_OnClick" runat="server" />
  <asp:CheckBox id="NotPublicCheckBox" runat="server" /> 
  Check here if this is <span style="text-decoration:underline">not</span> a public computer.

</form>

</body>
</html>
<%@ Page Language="VB" %>
<%@ Import Namespace="System.Web.Security" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">

Public Sub Login_OnClick(sender As Object, args As  EventArgs)

   If (Membership.ValidateUser(UsernameTextbox.Text, PasswordTextbox.Text)) Then
      FormsAuthentication.RedirectFromLoginPage(UsernameTextbox.Text, NotPublicCheckBox.Checked)
   Else
     Msg.Text = "Login failed. Please check your user name and password and try again."
   End If

End Sub

</script>

<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
  <title>Login</title>
</head>
<body>

<form id="form1" runat="server">
  <h3>Login</h3>

  <asp:Label id="Msg" ForeColor="maroon" runat="server" /><br />

  Username: <asp:Textbox id="UsernameTextbox" runat="server" /><br />
  Password: <asp:Textbox id="PasswordTextbox" runat="server" TextMode="Password" /><br />
 
  <asp:Button id="LoginButton" Text="Login" OnClick="Login_OnClick" runat="server" />
  <asp:CheckBox id="NotPublicCheckBox" runat="server" /> 
  Check here if this is <span style="text-decoration:underline">not</span> a public computer.

</form>

</body>
</html>

備註

表單驗證可讓使用者和密碼驗證,不需要 Windows 驗證的 Web 應用程式。Forms authentication enables user and password validation for Web applications that do not require Windows authentication. 使用表單驗證,使用者資訊會儲存在外部資料來源,例如Membership資料庫,或在應用程式的組態檔中。With forms authentication, user information is stored in an external data source, such as a Membership database, or in the configuration file for an application. 使用者驗證之後,表單驗證會維護在 cookie 中,或在 URL 中的驗證票證,讓已驗證的使用者不需要提供每個要求的認證。Once a user is authenticated, forms authentication maintains an authentication ticket in a cookie or in the URL so that an authenticated user does not need to supply credentials with each request.

藉由設定啟用表單驗證mode的屬性authentication組態項目FormsForms authentication is enabled by setting the mode attribute of the authentication configuration element to Forms. 您可以要求應用程式的所有要求,都包含使用有效的使用者驗證票證授權拒絕任何未知的使用者的要求,如下列範例所示的組態項目。You can require that all requests to an application contain a valid user authentication ticket by using the authorization configuration element to deny the request of any unknown user, as shown in the following example.

<system.web>  
  <authentication mode="Forms">  
    <forms loginUrl="login.aspx" />  
  </authentication>  
  <authorization>  
    <deny users="?" />  
  </authorization>  
</system.web>  

在上述範例中,ASP.NET 網頁應用程式一部分的任何要求需要表單驗證所提供的有效使用者名稱。In the previous example, any request for an ASP.NET page that is part of the application requires a valid user name that is supplied by forms authentication. 如果沒有使用者名稱存在,則會要求重新導向至已設定LoginUrlIf no user name exists, then the request is redirected to the configured LoginUrl.

FormsAuthentication類別提供方法和屬性,您可以使用驗證使用者的應用程式中的存取。The FormsAuthentication class provides access to methods and properties that you can use in an application that authenticates users. RedirectToLoginPage方法會在瀏覽器重新導向至已設定LoginUrl的使用者可以登入應用程式。The RedirectToLoginPage method redirects a browser to the configured LoginUrl for users to log into an application. RedirectFromLoginPage回到原始受保護的 URL 要求,或若要將已驗證的使用者重新導向的方法DefaultUrlThe RedirectFromLoginPage method redirects an authenticated user back to the original protected URL that was requested or to the DefaultUrl. 也有一些方法,如有需要請讓您管理表單驗證票證。There are also methods that enable you to manage forms-authentication tickets, if needed.

建構函式

FormsAuthentication() FormsAuthentication() FormsAuthentication() FormsAuthentication()

初始化 FormsAuthentication 類別的新執行個體。Initializes a new instance of the FormsAuthentication class.

屬性

CookieDomain CookieDomain CookieDomain CookieDomain

取得表單驗證 Cookie 的網域值。Gets the value of the domain of the forms-authentication cookie.

CookieMode CookieMode CookieMode CookieMode

取得表示應用程式是否針對 Cookieless 表單驗證進行設定的值。Gets a value that indicates whether the application is configured for cookieless forms authentication.

CookieSameSite CookieSameSite CookieSameSite CookieSameSite

取得或設定 Cookie 的 SameSite 屬性值。Gets or sets the value for the SameSite attribute of the cookie.

CookiesSupported CookiesSupported CookiesSupported CookiesSupported

取得表示應用程式是否設定為支援 Cookieless 表單驗證的值。Gets a value that indicates whether the application is configured to support cookieless forms authentication.

DefaultUrl DefaultUrl DefaultUrl DefaultUrl

取得未指定重新導向 URL 時,FormsAuthentication 類別將重新導向的 URL。Gets the URL that the FormsAuthentication class will redirect to if no redirect URL is specified.

EnableCrossAppRedirects EnableCrossAppRedirects EnableCrossAppRedirects EnableCrossAppRedirects

取得值,指出已驗證的使用者是否能重新導向至其他 Web 應用程式中的 URL。Gets a value indicating whether authenticated users can be redirected to URLs in other Web applications.

FormsCookieName FormsCookieName FormsCookieName FormsCookieName

取得用來存放表單驗證票證的 Cookie 名稱。Gets the name of the cookie used to store the forms-authentication ticket.

FormsCookiePath FormsCookiePath FormsCookiePath FormsCookiePath

取得表單驗證 Cookie 的路徑。Gets the path for the forms-authentication cookie.

IsEnabled IsEnabled IsEnabled IsEnabled

取得值,指出表單驗證是否已啟用。Gets a value that indicates whether forms authentication is enabled.

LoginUrl LoginUrl LoginUrl LoginUrl

取得 FormsAuthentication 類別將重新導向的登入網頁 URL。Gets the URL for the login page that the FormsAuthentication class will redirect to.

RequireSSL RequireSSL RequireSSL RequireSSL

取得值,指出表單驗證 Cookie 是否需要 SSL 才能傳回至伺服器。Gets a value indicating whether the forms-authentication cookie requires SSL in order to be returned to the server.

SlidingExpiration SlidingExpiration SlidingExpiration SlidingExpiration

取得一個指示是否啟用變動到期的值。Gets a value indicating whether sliding expiration is enabled.

TicketCompatibilityMode TicketCompatibilityMode TicketCompatibilityMode TicketCompatibilityMode

取得值,指出要使用 Coordinated Universal Time (UTC) 或當地時間做為票證到期日。Gets a value that indicates whether to use Coordinated Universal Time (UTC) or local time for the ticket expiration date.

Timeout Timeout Timeout Timeout

取得驗證票證逾期前的時間量。Gets the amount of time before an authentication ticket expires.

方法

Authenticate(String, String) Authenticate(String, String) Authenticate(String, String) Authenticate(String, String)

根據存放於應用程式組態檔中的認證,驗證使用者名稱和密碼。Validates a user name and password against credentials stored in the configuration file for an application.

Decrypt(String) Decrypt(String) Decrypt(String) Decrypt(String)

根據傳遞至方法的已加密表單驗證票證,建立 FormsAuthenticationTicket 物件。Creates a FormsAuthenticationTicket object based on the encrypted forms-authentication ticket passed to the method.

EnableFormsAuthentication(NameValueCollection) EnableFormsAuthentication(NameValueCollection) EnableFormsAuthentication(NameValueCollection) EnableFormsAuthentication(NameValueCollection)

啟用表單驗證。Enables forms authentication.

Encrypt(FormsAuthenticationTicket) Encrypt(FormsAuthenticationTicket) Encrypt(FormsAuthenticationTicket) Encrypt(FormsAuthenticationTicket)

建立包含已加密表單驗證票證 (適用於 HTTP Cookie 中) 的字串。Creates a string containing an encrypted forms-authentication ticket suitable for use in an HTTP cookie.

Equals(Object) Equals(Object) Equals(Object) Equals(Object)

判斷指定的物件是否等於目前的物件。Determines whether the specified object is equal to the current object.

(Inherited from Object)
GetAuthCookie(String, Boolean) GetAuthCookie(String, Boolean) GetAuthCookie(String, Boolean) GetAuthCookie(String, Boolean)

建立指定使用者名稱的驗證 Cookie。Creates an authentication cookie for a given user name. 這不會設定 Cookie 成為連出回應的一部分,因此應用程式更能夠控制如何發出 Cookie。This does not set the cookie as part of the outgoing response, so that an application can have more control over how the cookie is issued.

GetAuthCookie(String, Boolean, String) GetAuthCookie(String, Boolean, String) GetAuthCookie(String, Boolean, String) GetAuthCookie(String, Boolean, String)

建立指定使用者名稱的驗證 Cookie。Creates an authentication cookie for a given user name. 這不會將 Cookie 設定為外送回應的一部分。This does not set the cookie as part of the outgoing response.

GetHashCode() GetHashCode() GetHashCode() GetHashCode()

做為預設雜湊函式。Serves as the default hash function.

(Inherited from Object)
GetRedirectUrl(String, Boolean) GetRedirectUrl(String, Boolean) GetRedirectUrl(String, Boolean) GetRedirectUrl(String, Boolean)

傳回原始要求的重新導向 URL,此原始要求造成重新導向至登入網頁。Returns the redirect URL for the original request that caused the redirect to the login page.

GetType() GetType() GetType() GetType()

取得目前執行個體的 TypeGets the Type of the current instance.

(Inherited from Object)
HashPasswordForStoringInConfigFile(String, String) HashPasswordForStoringInConfigFile(String, String) HashPasswordForStoringInConfigFile(String, String) HashPasswordForStoringInConfigFile(String, String)

根據指定的密碼和雜湊演算法,產生適用於存放在組態檔中的雜湊密碼。Produces a hash password suitable for storing in a configuration file based on the specified password and hash algorithm.

Initialize() Initialize() Initialize() Initialize()

根據應用程式的組態設定,初始化 FormsAuthentication 物件。Initializes the FormsAuthentication object based on the configuration settings for the application.

MemberwiseClone() MemberwiseClone() MemberwiseClone() MemberwiseClone()

建立目前 Object 的淺層複製。Creates a shallow copy of the current Object.

(Inherited from Object)
RedirectFromLoginPage(String, Boolean) RedirectFromLoginPage(String, Boolean) RedirectFromLoginPage(String, Boolean) RedirectFromLoginPage(String, Boolean)

將已驗證的使用者重新導向回到原來要求的 URL 或預設 URL。Redirects an authenticated user back to the originally requested URL or the default URL.

RedirectFromLoginPage(String, Boolean, String) RedirectFromLoginPage(String, Boolean, String) RedirectFromLoginPage(String, Boolean, String) RedirectFromLoginPage(String, Boolean, String)

使用為表單驗證 Cookie 指定的 Cookie 路徑,將已驗證的使用者重新導向回到原先要求的 URL 或預設 URL。Redirects an authenticated user back to the originally requested URL or the default URL using the specified cookie path for the forms-authentication cookie.

RedirectToLoginPage() RedirectToLoginPage() RedirectToLoginPage() RedirectToLoginPage()

將瀏覽器重新導向至登入 URL。Redirects the browser to the login URL.

RedirectToLoginPage(String) RedirectToLoginPage(String) RedirectToLoginPage(String) RedirectToLoginPage(String)

將瀏覽器重新導向至包含指定查詢字串的登入 URL。Redirects the browser to the login URL with the specified query string.

RenewTicketIfOld(FormsAuthenticationTicket) RenewTicketIfOld(FormsAuthenticationTicket) RenewTicketIfOld(FormsAuthenticationTicket) RenewTicketIfOld(FormsAuthenticationTicket)

有條件地更新 FormsAuthenticationTicket 的核發日期和時間,以及到期日和時間。Conditionally updates the issue date and time and expiration date and time for a FormsAuthenticationTicket.

SetAuthCookie(String, Boolean) SetAuthCookie(String, Boolean) SetAuthCookie(String, Boolean) SetAuthCookie(String, Boolean)

為所提供的使用者名稱建立驗證票證,並將該票證加入至回應的 Cookie 集合,或加入至 URL (若使用的是 Cookieless 驗證)。Creates an authentication ticket for the supplied user name and adds it to the cookies collection of the response, or to the URL if you are using cookieless authentication.

SetAuthCookie(String, Boolean, String) SetAuthCookie(String, Boolean, String) SetAuthCookie(String, Boolean, String) SetAuthCookie(String, Boolean, String)

為所提供的使用者名稱建立驗證票證,並使用提供的 Cookie 路徑或使用 URL (若是使用 Cookieless 驗證),將該票證加入至回應的 Cookie 集合。Creates an authentication ticket for the supplied user name and adds it to the cookies collection of the response, using the supplied cookie path, or using the URL if you are using cookieless authentication.

SignOut() SignOut() SignOut() SignOut()

從瀏覽器移除表單驗證票證。Removes the forms-authentication ticket from the browser.

ToString() ToString() ToString() ToString()

傳回代表目前物件的字串。Returns a string that represents the current object.

(Inherited from Object)

安全性

AspNetHostingPermission
若要使用FormsAuthentication裝載環境中的類別。To use the FormsAuthentication class in a hosted environment. 要求值: LinkDemandDemand value: LinkDemand. 權限值: MinimalPermission value: Minimal.

適用於

另請參閱