How To: Use Membership in ASP.NET 2.0

 

Retired Content

This content is outdated and is no longer being maintained. It is provided as a courtesy for individuals who are still using these technologies. This page may contain URLs that were valid when originally published, but now link to sites or pages that no longer exist.

patterns & practices Developer Center

patterns & practices Developer Center

J.D. Meier, Alex Mackman, Blaine Wastell, Prashant Bansode, Andy Wigley, Kishore Gopalan

Microsoft Corporation

August 2005

Applies to

  • ASP.NET version 2.0
  • Microsoft® Active Directory® directory service
  • Microsoft SQL Server™ 2000

Summary

This How To shows how to use the membership feature in ASP.NET version 2.0 applications. It shows you how to use two different membership providers: the ActiveDirectoryMembershipProvider and the SqlMembershipProvider. The membership feature greatly reduces the amount of code you have to write to authenticate users at your Web site. The ActiveDirectoryMembership provider uses Microsoft® Active Directory® directory service to maintain user information, while the SqlMembershipProvider stores user details in a SQL Server database.

Contents

Objectives
Overview
Using the ActiveDirectoryMembershipProvider
Using the SQLMembershipProvider
ActiveDirectoryMembershipProvider Configuration Attributes
SqlMembershipProvider Configuration Attributes
Membership APIs
Additional Considerations
Additional Resources

Objectives

  • Learn to use membership with forms authentication.
  • Configure the ActiveDirectoryMembershipProvider for use with forms authentication.
  • Create and authenticate users by using the ActiveDirectoryMembershipProvider.
  • Configure the SqlMembershipProvider for use with forms authentication.
  • Set up the SQL Server membership database.
  • Create and authenticate users by using the SqlMembershipProvider.

Overview

The ASP.NET version 2.0 membership feature provides secure credential storage for application users. It also provides a membership API that simplifies the task of validating user credentials when used with forms authentication. Membership providers abstract the underlying store used to maintain user credentials. ASP.NET 2.0 includes the following providers:

  • ActiveDirectoryMembershipProvider. This uses either an Active Directory or Active Directory Application Mode (ADAM) user store.
  • SqlMembershipProvider. This uses a SQL Server user store.

With the pluggable membership architecture, you can also add support for your own user stores. For example, you can add support for other Lightweight Directory Access Protocol (LDAP) directories or other existing corporate identity stores. To do so, you create a custom provider that uses the MembershipProvider abstract class.

In most cases, the user store contains user credentials such as user names and passwords, and in some cases, personalization information. Avoid mixing personalization with authentication. If you only need to identify users for personalization reasons, a simple user name inside a cookie is sufficient. However, if you want to restrict and control access to different areas and functions of your Web site and if you need to audit operations attributed to different users, then you must use authenticated access and forms authentication.

Using the ActiveDirectoryMembershipProvider

You use the ActiveDirectoryMembershipProvider with forms authentication if your user information is stored in Active Directory. This situation normally occurs when you have an intranet application and you cannot use integrated Windows authentication because of firewalls or the need to accommodate mixed browser types.

Summary of Steps

Complete the following steps to configure and use the ActiveDirectoryMembershipProvider with an ASP.NET application that uses forms authentication.

  • Step 1. Configure forms authentication.
  • Step 2. Configure the ActiveDirectoryMembershipProvider.
  • Step 3. Create users.
  • Step 4. Authenticate users.

Step 1. Configure Forms Authentication

To configure forms authentication, set the <authentication> element's mode attribute to "Forms" and then configure your application's Web.config file as shown in the following example.

<authentication mode="Forms">
    <forms loginUrl="Login.aspx" 
           protection="All" 
           timeout="30" 
           name="AppNameCookie" 
           path="/FormsAuth" 
           requireSSL="false" 
           slidingExpiration="true" 
           defaultUrl="default.aspx"
           cookieless="UseCookies"
           enableCrossAppRedirects="false"/>
</authentication>
  

Where:

  • loginUrl points to the login page. You should place this in a folder that requires Secure Sockets Layer (SSL) for access.
  • protection is set to "All" to specify privacy and integrity for the forms authentication ticket.
  • timeout is used to specify a limited session lifetime.
  • name and path are set to unique values for the current application.
  • requireSSL is set to "false". This configuration means that authentication cookie can be transmitted over channels that are not SSL-protected. If you are concerned about session hijacking, you should consider setting this to "true". For more information, see Additional Considerations in this document.
  • slidingExpiration is set to "true" to enforce a sliding session lifetime. This means that the timeout is reset after each request to your application.
  • defaultUrl is set to the Default.aspx page for the application.
  • cookieless is set to "UseCookies" to specify that the application uses cookies to send the authentication ticket to the client.
  • enableCrossAppRedirects is set to "false" to indicate that the application cannot redirect requests outside the application scope.

Add the following <authorization> element after the <authentication> element. This permits only authenticated users to access the application. The previously established loginUrl attribute of the <authentication> element will redirect unauthenticated requests to the Login.aspx page.

<authorization> 
   <deny users="?" />
   <allow users="*" />
</authorization>
  

Step 2. Configure the ActiveDirectoryMembershipProvider

Configure the ActiveDirectoryMembershipProvider in your application's Web.config file as shown in the following example.

<connectionStrings>
  <add name="ADConnectionString" 
   connectionString=
    "LDAP://domain.testing.com/CN=Users,DC=domain,DC=testing,DC=com" />
</connectionStrings>

<system.web>
 ...
 <membership defaultProvider="MembershipADProvider">
  <providers>
    <add
      name="MembershipADProvider"
      type="System.Web.Security.ActiveDirectoryMembershipProvider, System.Web, 
            Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"
                connectionStringName="ADConnectionString" 
                connectionUsername="<domainName>\administrator" 
                connectionPassword="password"/>
   </providers>
 </membership>
 ...
</system.web>
  

The preceding code sample uses the <add> child element of the <providers> element to define a membership provider that uses the ActiveDirectoryMembershipProvider.

The connection string to the Active Directory user store is in the following format:

LDAP:// server/userdn

Where:

  • server is the name (or IP address) of the server that is hosting the directory.
  • userdn is the distinguished name (DN) of the Active Directory user store. This consists of /CN=Users which is the user store container name, followed by the partition, which is derived from the fully qualified domain name.

For example, if your domain is called domain.testing.com, the connection string is LDAP://domain.testing.com/CN=Users,DC=domain,DC=testing,DC=com.

Optionally, configure the credentials, using the connectionUserName and connectionPassword attributes, of an account capable of accessing Active Directory with the necessary permissions. If you do not specify account credentials, your application's process identity is used to access Active Directory, regardless of whether your application uses impersonation. Either the account specified in the Web.config file or your process account must have the appropriate permissions to access Active Directory.

Encrypt the connection strings element because it contains the network details. If you specify credentials in the ActiveDirectoryMembershipProvider configuration, encrypt the membership configuration element as well. You can use the Protected Configuration feature to encrypt the configuration section. For more information, see "How To: Encrypt Configuration Sections in ASP.NET 2.0 Using DPAPI" at https://msdn.microsoft.com/en-us/library/ms998280.aspx and "How To: Encrypt Configuration Sections in ASP.NET 2.0 Using RSA" at https://msdn.microsoft.com/en-us/library/ms998283.aspx.

Note   Make sure to set the defaultProvider attribute value of the <membership> element to the name of your ActiveDirectoryMembershipProvider (called MembershipADProvider in this example). You need to do this to override the machine-level default defined in the %windir%\Microsoft.NET\Framework\{Version}\Config\machine.config.comments file. This defines the defaultProvider to be AspNetSqlMembershipProvider, which is a provider that uses the SQLMembershipProvider to write to a SQL Server Express database in the \app_data folder of your application.

In addition to the above attributes, the ActiveDirectoryMembershipProvider has attributes that you can optionally overwrite. For more information, see ActiveDirectoryMembershipProvider Configuration Attributes in this document.

Step 3. Create Users

You can create new users in the following ways:

  • Use the Web Site Administration Tool, which provides a wizard-like interface for creating new users. To start this tool, click ASP.NET Configuration on the Website menu in the Microsoft Visual Studio® 2005 development system.
  • Create an ASP.NET page that contains a CreateUserWizard control. This control uses the configured membership provider to encapsulate the logic of creating a new user.
  • Create an ASP.NET Web page that contains TextBox controls to obtain the user name and password (and, optionally, the user's e-mail address), and then use the CreateUser Membership API method to programmatically create the new user.

Note   All of these techniques use the Membership.CreateUser method.

The default configuration for the ActiveDirectoryMembershipProvider uses user principal names (UPNs) for name mapping, as shown below:

attributeMapUsername="userPrincipalName"
  

Therefore all user names must have the following format:

UserName@DomainName
  

If you call Membership.CreateUser programmatically, use this format:

Membership.CreateUser("UserName@DomainName", "P@ssw0rd", "userName@emailAddress"); 
  

You can change the user mapping type by setting the following attribute in the Membership Provider configuration in the Web.config file.

attributeMapUsername="sAMAccountName"
  

With this configuration, supply user names in the following format:

UserName
  

For example:

Membership.CreateUser("UserName", "P@ssw0rd", "userName@emailAddress")
  

Note   You should set the requiresUniqueEmail attribute to "true" to ensure that users supply unique e-mail addresses.

Step 4. Authenticate Users

To authenticate users, you must provide a login form. This could be a separate page or a special area on your application's home page.

You can create the login form in the following ways::

  • Use the ASP.NET 2.0 login controls. The ASP.NET login controls encapsulate nearly all of the logic required to obtain credentials from users and to validate them against a user store. They use the configured membership provider. You do not need to write any additional code.

    After the user is validated, the login controls automatically save information about the user; for example, by using an encrypted cookie if the user's browser accepts cookies.

  • Create custom login forms by using ASP.NET TextBox controls. If you create a custom login form with simple TextBox controls, you can prompt the user for a user name and password, and then call the ValidateUser method of the Membership class to perform the validation.

    You also need to call methods of the FormsAuthentication class to create the cookie and write it to the user's computer, as shown in the following example.

    if (Membership.ValidateUser(userName.Text, password.Text))
    {
      if (Request.QueryString["ReturnUrl"] != null)
      {
        FormsAuthentication.RedirectFromLoginPage(userName.Text, false);
      }
      else
      {
        FormsAuthentication.SetAuthCookie(userName.Text, false);
      }
    }
    else
    {
      Response.Write("Invalid UserID and Password");
    }
    
    

    Note   Both of these techniques use the Membership.CreateUser method.

The default ActiveDirectoryMembershipProvider configuration uses user principal names (UPNs) for name mapping. If you call the Membership.ValidateUser method, be sure to use a UPN name as shown in the following example.

bool isValidUser = Membership.ValidateUser("UseName@DomainName", "P@ssw0rd"); 
  

You can change the mapping for each user by setting the following attribute in the Membership Provider configuration section of the Web.config file.

attributeMapUsername="sAMAccountName"
  

With this configuration, you must call Membership.ValidateUser as shown here in the following example.

bool isValidUser = Membership.ValidateUser("UserName", "P@ssw0rd", "userName@emailAddress")
  

Using the SQLMemberShipProvider

You use the SQLMembershipProvider with forms authentication if your user information is stored in SQL Server. In most cases, this occurs when you have an intranet and user information is application-specific or when the application is Internet facing and the users do not have Active Directory accounts.

When you install ASP.NET, the Machine.config file for your server includes configuration elements that specify SQL Server membership providers. By default, the SQL provider is configured to connect to the local instance of SQL Server.

Summary of Steps

Complete the following steps to configure and use the SqlMembershipProvider with an ASP.NET application that uses forms authentication.

  • Step 1. Configure forms authentication.
  • Step 2. Install the membership database.
  • Step 3. Configure the SqlMembershipProvider.
  • Step 4. Create users.
  • Step 5. Authenticate users.

Step 1. Configure Forms Authentication

Set the <authentication> element's mode attribute to "Forms" and then configure it in your application's Web.config file, as shown in the following example

<authentication mode="Forms">
   <forms loginUrl="Login.aspx" 
          protection="All" 
          timeout="30" 
          name="AppNameCookie" 
          path="/FormsAuth" 
          requireSSL="false" 
          slidingExpiration="true" 
          defaultUrl="default.aspx"
          cookieless="UseCookies"
          enableCrossAppRedirects="false" />
</authentication>
 
  

Where:

  • loginUrl points to the login page. You should place this in a folder that requires Secure Sockets Layer (SSL) for access.
  • protection is set to "All" to specify privacy and integrity for the forms authentication ticket.
  • timeout is used to specify a limited session lifetime.
  • name and path are set to unique values for the current application.
  • requireSSL is set to "false". This configuration means that authentication cookie can be transmitted over channels that are not SSL-protected. If you are concerned with session hijacking, you should consider setting this to "true". For more information, see Additional Considerations in this document.
  • slidingExpiration is set to "true" to enforce a sliding session lifetime. This means that the timeout is reset after each request to your application.
  • defaultUrl is set to the Default.aspx page for the application.
  • cookieless is set to "UseCookies" to specify that the application uses cookies to send the authentication ticket to the client.
  • enableCrossAppRedirects is set to "false", to indicate that the application cannot redirect the request outside the application scope.

Add the following <authorization> element after the <authentication> element. This permits only authenticated users to access the application. The previously established loginUrl attribute of the <authentication> element redirects unauthenticated requests to the Login.aspx page.

<authorization> 
   <deny users="?" />
   <allow users="*" />
 </authorization>
  

Step 2. Install the Membership Database

Before you can use the SqlMembershipProvider, you must install the SQL Server membership database.

To install the membership database, log on to your server with an account that has authority to administrate SQL Server (such as the Administrator account). Open the Visual Studio 2005 command prompt, and run the following command:

aspnet_regsql.exe -E -S localhost -A m

Where:

  • -E indicates authenticate using the Windows credentials of the currently logged on user.
  • -S (server) indicates the name of the server where the database will be installed or is already installed.
  • -A m indicates add membership support. This creates the tables and stored procedures required by the membership provider.

Note   The Aspnet_regsql tool is also used to install database elements for other ASP.NET 2.0 features, such as Role Management, Profile, Web Parts Personalization, and Web Events. Other command-line arguments perform database operations for these other features. You can use Aspnet_regsql without any command line arguments by using a wizard that allows you to specify connection information for your SQL Server and install or remove the database elements for all of the supported features.

Step 3. Configure the SqlMembershipProvider

The Machine.config file contains a default SqlMembershipProvider instance named AspNetSqlMembershipProvider that connects to the SQL Server Express instance on the local computer. You can use this instance of the provider if you are running SQL Server locally. Alternatively, you can specify provider details in your application's Web.config file, as shown here in the following example.

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

Important   Ensure that the ASP.NET process identity (or, if using impersonation, the impersonated identity) have appropriate permissions on the SQL Server database.

Encrypt the connection strings element using Protected Configuration because this element contains the database connection details. For more information on encrypting the configuration section, see "How To: Encrypt Configuration Sections in ASP.NET 2.0 Using DPAPI" at https://msdn.microsoft.com/en-us/library/ms998280.aspx and "How To: Encrypt Configuration Sections in ASP.NET 2.0 Using RSA" at https://msdn.microsoft.com/en-us/library/ms998283.aspx.

Make sure to set the defaultProvider attribute value to point to your provider definition. The default value points to AspNetSqlProvider, which uses the local SqlExpress instance.

For more information, see the section, "SqlProviderMembershipProvider Configuration Attributes," in this document.

Step 4. Create Users

You can create new users in the following ways:

  • Use the Web Site Administration Tool, which provides a wizard-like interface for creating new users. To start this tool, click ASP.NET Configuration on the Website menu in Visual Studio 2005.
  • Create an ASP.NET page that contains a CreateUserWizard control. This control uses the configured membership provider to encapsulate the logic of creating a new user.
  • Create an ASP.NET Web page that contains the TextBox controls used to collect the user name and password (and, optionally, the user's e-mail address), and then use the Membership.CreateUser API to create a new user in the membership system.

The following code shows how to call Membership CreateUser.

Membership.CreateUser("Username", "P@ssw0rd", "userName@emailAddress"); 
  

Step 5. Authenticate Users

To authenticate users, you must provide a login form. This could be a separate page or a special area on your application's home page.

You can create the login form in the following ways:

  • Use the ASP.NET 2.0 login controls. The ASP.NET login controls encapsulate nearly all of the logic required to obtain credentials from users and to validate them against a user store. They use the configured membership provider. You do not need to write any additional code.

    After the user is validated, the login controls automatically save information about the user; for example, by using an encrypted cookie if the user's browser accepts cookies.

  • Create a custom login form by using ASP.NET TextBox controls. If you create a custom login form with simple TextBox controls, you can prompt the user for a user name and password, and then call the ValidateUser method of the Membership class to perform the validation.

ActiveDirectoryMembershipProvider Configuration Attributes

Table 1 lists the ActiveDirectoryMembershipProvider configuration attributes, their default values, and notes for their usage.

Table 1: ActiveDirectoryMembershipProvider Configuration Attributes

Attribute Default Value Notes
connectionStringName   Points to a connection string contained in the connection strings configuration section. This attribute is required because it points to the primary LDAP bind string that is used for create, update, get, and validate operations.
connectionUserName   Defines the user name used for authentication purposes when connecting to the directory. If this attribute is specified, the companion connectionPassword attribute must also be specified. This attribute is used to configure a set of credentials that can be used to connect to the directory (instead of using the process account or impersonation credentials that are in effect at the time the provider connects to the directory).
connectionPassword   Defines the password used for authentication purposes when connecting to the directory. If this attribute is specified, the companion connectionUserName attribute must also be specified. This attribute is used to configure a set of credentials that can be used to connect to the directory (instead of using the process account or impersonation credentials that are in effect at the time the provider connects to the directory).
connectionProtection Secure Defines the transport layer security options that are used when opening connections to the directory. This attribute can have a string value of "Secure" or "None".

If set to "Secure", the provider attempts to select the highest level of connection security available, based on the type of directory that the provider connects to. The protection is determined as follows:
SSL is first attempted because SSL is an option that works with both Active Directory and ADAM (ActiveDirectoryConnection
Protection.Ssl)
.
If SSL is not available and the provider is connecting to Active Directory or to a domain-joined ADAM instance, encrypt-sign-and-seal is used (ActiveDirectoryConnection
Protection.SignAndSeal
).
If neither SSL nor encrypt-sign-seal is available, the provider generates a ProviderException, stating that it could not automatically select a secure connection to the configured directory.

enablePasswordReset False Controls whether or not a password can be reset. For security reasons, with the ActiveDirectoryMembershipProvider, this attribute can only be set to true if all of the following have been set:
requiresQuestionAndAnswer is set to true.
passwordQuestion, passwordAnswer, attributeMapFailedPasswordAnswer
Count
, attributeMapFailedPassword
AnswerTime
, and attributeMapFailed
PasswordAnswerLockoutTime
have been mapped to attributes in the directory.
Note: Even if this attribute is set to true, password resets are allowed only if the credentials used to perform the reset have Administrator privileges in Active Directory..
enableSearchMethods False Allows an administrator to set whether or not search-oriented methods can be called on the provider instance. Because methods such as Find* and GetAllUsers can be very expensive, the default value for this attribute is false.
The following methods throw a NotSupportedException if they are called when this attribute is set to false:
FindUsersByName
FindUsersByEmail
GetAllUsers
requiresQuestionAnd
Answer
False Determines whether a password question and answer are required for a password reset.

For security reasons, with ActiveDirectoryMembership
Provider
, this attribute can only be set to true if all of the following have been set:
attributeMapPasswordQuestion, attributeMapPasswordAnswer, attributeMapFailedPasswordAnswerCount, attributeMapFailedPasswordAnswerTime, and attributeMapFailedPasswordAnswerLockoutTime

applicationName / For this provider, applicationName is included for completeness with other providers. Internally, it does not matter what value is placed here because the application name is not used. The maximum value is 256 characters.
requiresUniqueEmail False Specifies whether the e-mail values used in the application must be unique.
maxInvalidPassword
Attempts
5 Indicates the number of failed password attempts or failed password answer attempts allowed before a user's account is locked. When the number of failed attempts equals the value set in this attribute, the user's account is locked out.

For the Active Directory provider, this attribute applies only to managing resets that use a password answer. Active Directory manages bad password attempts internally.

passwordAttempt
Window
10 Indicates the time window, in minutes, during which failed password attempts and failed password answer attempts are tracked.

For the Active Directory provider, this attribute applies only to managing resets that use a password answer. Active Directory manages bad password attempts internally.

passwordAnswer
AttemptLockout
Duration
30 Specifies the duration, in minutes, that a lockout due to a bad password answer is considered still in effect. Because Active Directory uses the concept of timing out bad password lockouts, this attribute is necessary to support a similar concept of timing bad password answer attempts.
minRequiredPassword
Length
7 Specifies the minimum number of characters required in a password. The value can be from 1 to 128.
minRequiredNonAlpha
numericCharacters
1 Specifies the minimum number of non-alphanumeric characters required in a password. This configuration attribute cannot be set to a value greater than the value of the minRequiredPasswordLength. This means the configuration setting must be in the range of
0–minRequiredPasswordLength, inclusive of minRequiredPasswordLength.
passwordStrength
RegularExpression
"" Provides a valid regular expression that the provider will use as part of password strength validation.
attributeMapUsername userPrincipalName Defines the mapping from a property on a MembershipUser object to an attribute within the directory.
The only directory attributes for mapping to a username if you are using Active Directory are userPrincipalName or sAMAccountName. The only allowed directory attributes for mapping to username if you are using ADAM is userPrincipalName.
attributeMapEmail Mail Defines the mapping from a property on a MembershipUser object to an attribute within the directory.
attributeMapPassword
Question
UNDEFINED Defines the mapping from a property on a MembershipUser object to an attribute within the directory.
attributeMapPassword
Answer
UNDEFINED Defines the mapping from a property on a MembershipUser object to an attribute within the directory.
attributeMapFailed
PasswordAnswerCount
UNDEFINED Defines the mapping from a property on a MembershipUser object to an attribute within the directory.
attributeMapFailed
PasswordAnswerTime
UNDEFINED Defines the mapping from a property on a MembershipUser object to an attribute within the directory.
attributeMapFailed
PasswordAnswer
LockoutTime
UNDEFINED Defines the mapping from a property on a MembershipUser object to an attribute within the directory.

When the requiresQuestionAndAnswer attribute is set to true, the ActiveDirectoryMembershipProvider class supports password reset security by requiring the user to answer a predetermined question.

To support the question and answer, you must set the attributeMapPasswordQuestion and attributeMapPasswordAnswer attributes when you use the <add> element to add the ActiveDirectoryMembershipProvider object after the membership <providers> element.

For more information, see How To: Use Forms Authentication with Active Directory in ASP.NET 2.0.

SqlMembershipProvider Configuration Attributes

Table 2 lists the SqlMembershipProvider configuration attributes, their default values, and notes for their usage.

Table 2. SqlMembershipProvider Configuration Attributes

Attribute Default Value Notes
connectionStringName   Points to a connection string contained in the connection strings configuration section. This attribute is required because it points to the SQL connection string used for connecting to the SQL server database instance.
enablePasswordReset False Controls whether or not a password can be reset.
For security reasons, with the SqLMembershipProvider, this attribute can only be set to true if all of the following have been set:
requiresQuestionAndAnswer set to true
passwordQuestion
passwordAnswer
requiresQuestionAnd
Answer
False Determines whether a password question and answer are required for a password reset.
applicationName / Used to group user information. By qualifying user information with an application name, you can store information for multiple applications in a single database without running into conflicts between duplicate user names. Also, multiple ASP.NET applications can use the same user database by specifying the same value in the applicationName attribute. The maximum value allowed is 256 characters.
requiresUniqueEmail False Specifies whether the e-mail values used in the application must be unique.
maxInvalidPassword
Attempts
5 Indicates the number of failed password attempts or failed password answer attempts allowed before a user's account is locked. When the number of failed attempts equals the value set in this attribute, the user's account is locked out.
passwordAttempt
Window
10 Indicates the time window, in minutes, during which failed password attempts and failed password answer attempts are tracked.
passwordFormat   Specifies the password format. The SQL Server membership provider supports Clear, Encrypted, and Hashed password formats. Clear passwords are stored in plain text, which improves the performance of password storage and retrieval, but is less secure because passwords are easily read if your SQL Server database is compromised. Encrypted passwords are encrypted when stored and can be decrypted for password comparison or password retrieval. This requires additional processing for password storage and retrieval, but is more secure because passwords are not easily deciphered if the SQL Server database is compromised. Hashed passwords are hashed using a one-way hash algorithm and a randomly generated salt value when stored in the database. When a password is validated, it is hashed with the salt value in the database for verification. Hashed passwords cannot be retrieved.
passwordAnswer
AttemptLockout
Duration
30 Specifies the duration, in minutes, that a lockout due to a bad password answer is still in effect.
minRequiredPassword
Length
7 Specifies the minimum number of characters required in a password. The value can be from 1 to 128.
minRequiredNonAlpha
numericCharacters
1 Specifies the minimum number of non-alphanumeric characters required in a password. This configuration attribute cannot be set to a value greater than the value of the minRequiredPassword
Length
. This means the configuration setting must be in the range of
0minRequiredPasswordLength, inclusive of minRequiredPasswordLength.
passwordStrength
RegularExpression
"" Provides a valid regular expression that the provider will use as part of password strength validation.

Membership APIs

Table 3 lists some of the more important methods of the Membership class, along with their parameters and usage notes.

Table 3. Membership Class Methods

Method Parameters Notes
CreateUser string username–User name to create.
string password–Password for new user
string email–E-mail for new user.
string passwordQuestion
string passwordAnswer
bool IsApproved
object providerUserKey
Used to create a new user.
DeleteUser string username–User to delete.
bool removeAllRelatedData
Used to immediately remove a user identified by the supplied username. Returns true if the user was deleted or false if not found.
FindUsersByName string usernameToMatch
int pageIndex
int pageSize
Returns a collection of users where the string parameter passed matches part of the username.
Wildcard support depends on how each data store handles characters such as "*", "%" and "_".
FindUsersByEmail string emailToMatch
int pageIndex
int pageSize
Returns a collection of users whose e-mail addreses matches any part of the string parameter passed.
Wildcard support depends on how each data store handles characters such as "*", "%" and "_"
GeneratePassword int length
Int numberOfNonAlpha
NumericCharacters
Returns a password of the specified length that contains the specified number of non-alphanumeric characters.
GetAllUsers int pageIndex
int pageSize
Returns a subset of users from the collection of all users. The subset is based on the pageIndex and pageSize methods.
GetNumberOfUsersOnline None Returns a count of all the users who are currently online
The Active Directory provider does not implement this functionality
GetUsernameByEmail string email–Email of user to lookup. Return a member's username.
UpdateUser MembershipUseruser–Membership user to update Updates a member's properties; for example, an e-mail address.
ValidateUser string username–User name to validate.
string password–User password to validate.
Validates a user's credentials. Returns true if the credentials are valid and false if they are not.
With Active Directory, regardless of the configured connection credentials, the provider connects to the directory with the username and password parameter as the connection credentials.

Note   The GetAllUsers method will be removed in the RTM version of .NET Framework 2.0.

Additional Considerations

Forms authentication requires the user to enter a username and password into a Web page, which is then transmitted in plaintext (by default) over the network. To prevent these credentials from being stolen, you should install a server certificate on your Web server and configure your Web site to require SSL.

To ensure that forms authentication tickets may only be transmitted over SSL-secured channels, set the requireSSL attribute of the <forms> element to true. The following code sample shows how to do this, and also demonstrates how to ensure that your users access the login page by using SSL, whether or not they entered the URL of your application's main page using HTTP:// or HTTPS://. To verify that SSL is used, you can enter a full URL to the login page in the loginUrl attribute, but if you do this, you must configure unrestricted access to the login page by using the configuration shown inside the <location> tag.

<configuration>
  <system.web>
    <authentication mode="Forms">
        <forms loginUrl="https://myserver/mywebapp/secure/Login.aspx" 
               protection="All" 
               timeout="30" 
               name="AppNameCookie" 
               path="/FormsAuth" 
               requireSSL="true" 
               slidingExpiration="true" 
               defaultUrl="default.aspx"
               cookieless="UseCookies"
               enableCrossAppRedirects="false"/>
    </authentication>

    <!-- Deny access to unauthenticated users -->
    <authorization> 
       <deny users="?" />
       <allow users="*" />
     </authorization>
  </system.web>
</configuration>

<!-- Allow unrestricted access to the folder with the login page -->
<location path="secure">
  <system.web>
    <authorization> 
       <allow users="*" />
     </authorization>
  </system.web>
</location>
  

Additional Resources

Feedback

Provide feedback by using either a Wiki or e-mail:

We are particularly interested in feedback regarding the following:

  • Technical issues specific to recommendations
  • Usefulness and usability issues

Technical Support

Technical support for the Microsoft products and technologies referenced in this guidance is provided by Microsoft Support Services. For product support information, please visit the Microsoft Support Web site at https://support.microsoft.com.

Community and Newsgroups

Community support is provided in the forums and newsgroups:

To get the most benefit, find the newsgroup that corresponds to your technology or problem. For example, if you have a problem with ASP.NET security features, you would use the ASP.NET Security forum.

Contributors and Reviewers

  • External Contributors and Reviewers: Eric Marvets, Dunn Training and Consulting; Jason Taylor, Security Innovation; Rudolph Araujo, Foundstone Professional Services
  • Microsoft Consulting Services and PSS Contributors and Reviewers: Adam Semel, Tom Christian, Wade Mascia
  • Microsoft Product Group Contributors and Reviewers: Stefan Schackow
  • Test team: Larry Brader, Microsoft Corporation; Nadupalli Venkata Surya Sateesh and Sivanthapatham Shanmugasundaram, Infosys Technologies Ltd.
  • Edit team: Nelly Delgado, Microsoft Corporation; Tina Burden, TinaTech
  • Release Management: Sanjeev Garg, Microsoft Corporation

patterns & practices Developer Center

Retired Content

This content is outdated and is no longer being maintained. It is provided as a courtesy for individuals who are still using these technologies. This page may contain URLs that were valid when originally published, but now link to sites or pages that no longer exist.