Muokkaa

Jaa


Membership Class

Definition

Validates user credentials and manages user settings. This class cannot be inherited.

public ref class Membership abstract sealed
public static class Membership
type Membership = class
Public Class Membership
Inheritance
Membership

Examples

The following code example shows the login page for an ASP.NET application configured to use forms authentication and ASP.NET membership. If the supplied user credentials are invalid, a message is displayed to the user. Otherwise, the user is redirected to the originally requested URL using the RedirectFromLoginPage method.

Note

The ASP.NET login controls (Login, LoginView, LoginStatus, LoginName, and PasswordRecovery) encapsulate virtually all of the logic required to prompt users for credentials and validate the credentials in the membership system and can be used in place of programmatic checking using the Membership class.

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

The Membership class is used in ASP.NET applications to validate user credentials and manage user settings such as passwords and email addresses. The Membership class can be used on its own, or in conjunction with the FormsAuthentication to create a complete system for authenticating users of a Web application or site. The Login control encapsulates the Membership class to provide a convenient mechanism for validating users.

Note

If you are not familiar with the membership features of ASP.NET, see Introduction to Membership before continuing. For a list of other topics related to membership, see Managing Users by Using Membership.

The Membership class provides facilities for:

  • Creating new users.

  • Storing membership information (user names, passwords, email addresses, and supporting data) in Microsoft SQL Server or in an alternative data store.

  • Authenticating users who visit your site. You can authenticate users programmatically, or you can use the Login control to create a complete authentication system that requires little or no code.

  • Managing passwords, which includes creating, changing, retrieving, and resetting them, and so on. You can optionally configure ASP.NET membership to require a password question and answer to authenticate password reset or retrieval requests for users that have forgotten their password.

Although ASP.NET membership is a self-standing feature in ASP.NET For authentication, it can be integrated with ASP.NET role management to provide authorization services for your site. Membership can also be integrated with the ASP.NET user System.Web.Profile to provide application-specific customization that can be tailored to individual users. For details, see Understanding Role Management and ASP.NET Profile Properties Overview.

The Membership class relies on membership providers to communicate with a data source. The .NET Framework includes a SqlMembershipProvider, which stores user information in a Microsoft SQL Server database, and an ActiveDirectoryMembershipProvider, which enables you to store user information on an Active Directory or Active Directory Application Mode (ADAM) server. You can also implement a custom membership provider to communicate with an alternative data source that can be used by the Membership class. Custom membership providers inherit the MembershipProvider abstract class. For more information, see Implementing a Membership Provider.

By default, ASP.NET membership is enabled for all ASP.NET applications. The default membership provider is the SqlMembershipProvider and is specified in the machine configuration with the name AspNetSqlProvider. The default instance of the SqlMembershipProvider is configured to connect to a local instance of Microsoft SQL Server.

You can modify the default settings to specify a SqlMembershipProvider other than the AspNetSqlProvider instance as the default provider, or specify an instance of a custom provider as the default provider for your ASP.NET application using the Web.config file. You can specify the ASP.NET membership configuration for your Web application using the membership configuration section in the Web.config file. You can use the providers subsection of the membership section to specify a membership provider other than one of the default providers. For example, the following membership section removes the default membership providers from the current application configuration and adds a new provider with a name of SqlProvider that connects to a SQL Server instance named AspSqlServer.

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

Properties

ApplicationName

Gets or sets the name of the application.

EnablePasswordReset

Gets a value indicating whether the current membership provider is configured to allow users to reset their passwords.

EnablePasswordRetrieval

Gets a value indicating whether the current membership provider is configured to allow users to retrieve their passwords.

HashAlgorithmType

The identifier of the algorithm used to hash passwords.

MaxInvalidPasswordAttempts

Gets the number of invalid password or password-answer attempts allowed before the membership user is locked out.

MinRequiredNonAlphanumericCharacters

Gets the minimum number of special characters that must be present in a valid password.

MinRequiredPasswordLength

Gets the minimum length required for a password.

PasswordAttemptWindow

Gets the time window between which consecutive failed attempts to provide a valid password or password answer are tracked.

PasswordStrengthRegularExpression

Gets the regular expression used to evaluate a password.

Provider

Gets a reference to the default membership provider for the application.

Providers

Gets a collection of the membership providers for the ASP.NET application.

RequiresQuestionAndAnswer

Gets a value indicating whether the default membership provider requires the user to answer a password question for password reset and retrieval.

UserIsOnlineTimeWindow

Specifies the number of minutes after the last-activity date/time stamp for a user during which the user is considered online.

Methods

CreateUser(String, String, String, String, String, Boolean, MembershipCreateStatus)

Adds a new user with specified property values to the data store and returns a status parameter indicating that the user was successfully created or the reason the user creation failed.

CreateUser(String, String, String, String, String, Boolean, Object, MembershipCreateStatus)

Adds a new user with specified property values and a unique identifier to the data store and returns a status parameter indicating that the user was successfully created or the reason the user creation failed.

CreateUser(String, String, String)

Adds a new user with a specified email address to the data store.

CreateUser(String, String)

Adds a new user to the data store.

DeleteUser(String, Boolean)

Deletes a user from the database.

DeleteUser(String)

Deletes a user and any related user data from the database.

FindUsersByEmail(String, Int32, Int32, Int32)

Gets a collection of membership users, in a page of data, where the email address contains the specified email address to match.

FindUsersByEmail(String)

Gets a collection of membership users where the email address contains the specified email address to match.

FindUsersByName(String, Int32, Int32, Int32)

Gets a collection of membership users, in a page of data, where the user name contains the specified user name to match.

FindUsersByName(String)

Gets a collection of membership users where the user name contains the specified user name to match.

GeneratePassword(Int32, Int32)

Generates a random password of the specified length.

GetAllUsers()

Gets a collection of all the users in the database.

GetAllUsers(Int32, Int32, Int32)

Gets a collection of all the users in the database in pages of data.

GetNumberOfUsersOnline()

Gets the number of users currently accessing an application.

GetUser()

Gets the information from the data source and updates the last-activity date/time stamp for the current logged-on membership user.

GetUser(Boolean)

Gets the information from the data source for the current logged-on membership user. Updates the last-activity date/time stamp for the current logged-on membership user, if specified.

GetUser(Object, Boolean)

Gets the information from the data source for the membership user associated with the specified unique identifier. Updates the last-activity date/time stamp for the user, if specified.

GetUser(Object)

Gets the information from the data source for the membership user associated with the specified unique identifier.

GetUser(String, Boolean)

Gets the information from the data source for the specified membership user. Updates the last-activity date/time stamp for the user, if specified.

GetUser(String)

Gets the information from the data source for the specified membership user.

GetUserNameByEmail(String)

Gets a user name where the email address for the user matches the specified email address.

UpdateUser(MembershipUser)

Updates the database with the information for the specified user.

ValidateUser(String, String)

Verifies that the supplied user name and password are valid.

Events

ValidatingPassword

Occurs when a user is created, a password is changed, or a password is reset.

Applies to

See also