FormsAuthentication FormsAuthentication FormsAuthentication FormsAuthentication Class

Definition

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
Inheritance
FormsAuthenticationFormsAuthenticationFormsAuthenticationFormsAuthentication

Examples

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>  

The following code example shows the login page for an ASP.NET application that uses forms authentication and ASP.NET membership.

Important

This example contains a text box that accepts user input, which is a potential security threat. By default, ASP.NET Web pages validate that user input does not include script or HTML elements. 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>

Remarks

Forms authentication enables user and password validation for Web applications that do not require Windows authentication. 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. 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.

Forms authentication is enabled by setting the mode attribute of the configuration element to Forms. You can require that all requests to an application contain a valid user authentication ticket by using the 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>  

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. If no user name exists, then the request is redirected to the configured LoginUrl.

The FormsAuthentication class provides access to methods and properties that you can use in an application that authenticates users. The RedirectToLoginPage method redirects a browser to the configured LoginUrl for users to log into an application. The 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.

Constructors

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

Initializes a new instance of the FormsAuthentication class.

Properties

CookieDomain CookieDomain CookieDomain CookieDomain

Gets the value of the domain of the forms-authentication cookie.

CookieMode CookieMode CookieMode CookieMode

Gets a value that indicates whether the application is configured for cookieless forms authentication.

CookieSameSite CookieSameSite CookieSameSite CookieSameSite

Gets or sets the value for the SameSite attribute of the cookie.

CookiesSupported CookiesSupported CookiesSupported CookiesSupported

Gets a value that indicates whether the application is configured to support cookieless forms authentication.

DefaultUrl DefaultUrl DefaultUrl DefaultUrl

Gets the URL that the FormsAuthentication class will redirect to if no redirect URL is specified.

EnableCrossAppRedirects EnableCrossAppRedirects EnableCrossAppRedirects EnableCrossAppRedirects

Gets a value indicating whether authenticated users can be redirected to URLs in other Web applications.

FormsCookieName FormsCookieName FormsCookieName FormsCookieName

Gets the name of the cookie used to store the forms-authentication ticket.

FormsCookiePath FormsCookiePath FormsCookiePath FormsCookiePath

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

Gets the URL for the login page that the FormsAuthentication class will redirect to.

RequireSSL RequireSSL RequireSSL RequireSSL

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

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.

Methods

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)

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)

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)

Creates an authentication cookie for a given user name. 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)

Creates an authentication cookie for a given user name. 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)

Returns the redirect URL for the original request that caused the redirect to the login page.

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

Gets 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()

Initializes the FormsAuthentication object based on the configuration settings for the application.

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

Creates a shallow copy of the current Object.

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

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)

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()

Redirects the browser to the login URL.

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

Redirects the browser to the login URL with the specified query string.

RenewTicketIfOld(FormsAuthenticationTicket) RenewTicketIfOld(FormsAuthenticationTicket) RenewTicketIfOld(FormsAuthenticationTicket) RenewTicketIfOld(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)

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)

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)

Security

AspNetHostingPermission
To use the FormsAuthentication class in a hosted environment. Demand value: LinkDemand. Permission value: Minimal.

Applies to