Export (0) Print
Expand All

WebSecurity Class

Provides security and authentication features for ASP.NET Web Pages applications, including the ability to create user accounts, log users in and out, reset or change passwords, and perform related tasks.

System.Object
  WebMatrix.WebData.WebSecurity

Namespace:  WebMatrix.WebData
Assembly:  WebMatrix.WebData (in WebMatrix.WebData.dll)

public static class WebSecurity

The WebSecurity type exposes the following members.

  NameDescription
Public propertyStatic memberCurrentUserIdGets the ID for the current user.
Public propertyStatic memberCurrentUserNameGets the user name for the current user.
Public propertyStatic memberHasUserIdGets a value that indicates whether the current user has a user ID.
Public propertyStatic memberIsAuthenticatedGets the authentication status of the current user.
Top

  NameDescription
Public methodStatic memberChangePasswordChanges the password for the specified user.
Public methodStatic memberConfirmAccountConfirms that an account is valid and activates the account.
Public methodStatic memberCreateAccountCreates a new membership account using the specified user name and password and optionally lets you specify that the user must explicitly confirm the account.
Public methodStatic memberCreateUserAndAccountCreates a new user profile entry and a new membership account.
Public methodStatic memberGeneratePasswordResetTokenGenerates a password reset token that can be sent to a user in email.
Public methodStatic memberGetCreateDateReturns the date and time when the specified membership account was created.
Public methodStatic memberGetLastPasswordFailureDateReturns the date and time when an incorrect password was most recently entered for the specified account.
Public methodStatic memberGetPasswordChangedDateReturns the date and time when the password was most recently changed for the specified membership account.
Public methodStatic memberGetPasswordFailuresSinceLastSuccessReturns the number of times that the password for the specified account was incorrectly entered since the last successful login or since the membership account was created.
Public methodStatic memberGetUserIdReturns the ID for a user based on the specified user name.
Public methodStatic memberGetUserIdFromPasswordResetTokenReturns a user ID from a password reset token.
Public methodStatic memberInitializeDatabaseConnection(String, String, String, String, Boolean)Initializes the membership system by connecting to a database that contains user information and optionally creates membership tables if they do not already exist.
Public methodStatic memberInitializeDatabaseConnection(String, String, String, String, String, Boolean)Initializes the membership system by connecting to a database that contains user information by using the specified membership or role provider, and optionally creates membership tables if they do not already exist.
Public methodStatic memberIsAccountLockedOut(String, Int32, Int32)Returns a value that indicates whether the specified membership account is temporarily locked because of too many failed password attempts in the specified number of seconds.
Public methodStatic memberIsAccountLockedOut(String, Int32, TimeSpan)Returns a value that indicates whether the specified membership account is temporarily locked because of too many failed password attempts in the specified time span.
Public methodStatic memberIsConfirmedReturns a value that indicates whether the user has been confirmed.
Public methodStatic memberIsCurrentUserReturns a value that indicates whether the user name of the logged-in user matches the specified user name.
Public methodStatic memberLoginLogs the user in.
Public methodStatic memberLogoutLogs the user out.
Public methodStatic memberRequireAuthenticatedUserIf the user is not authenticated, sets the HTTP status to 401 (Unauthorized).
Public methodStatic memberRequireRolesIf the current user is not in all of the specified roles, sets the HTTP status code to 401 (Unauthorized).
Public methodStatic memberRequireUser(Int32)If the specified user is not logged on, sets the HTTP status to 401 (Unauthorized).
Public methodStatic memberRequireUser(String)If the current user does not match the specified user name, sets the HTTP status to 401 (Unauthorized).
Public methodStatic memberResetPasswordResets a password by using a password reset token.
Public methodStatic memberUserExistsReturns a value that indicates whether the specified user exists in the membership database.
Top

  NameDescription
Public fieldStatic memberEnableSimpleMembershipKeyRepresents the key to the enableSimpleMembership value in the AppSettings property.
Top

This class represents a helper, which is a component that simplifies web programming in ASP.NET Web Pages. The WebSecurity class is the primary means in ASP.NET Web Pages to perform security operations. It exposes the most frequently required security features, such as creating a user account, logging users in and out, getting details about a user, changing a password, and so on. Typical tasks for using WebSecurity include the following:

Behind the scenes, the WebSecurity class interacts with an ASP.NET membership provider that in turn performs the lower-level work that is required in order to perform security tasks. The default membership provider in ASP.NET Web Pages is the SimpleMembershipProvider class.

By design, the WebSecurity class does not expose (nor does the SimpleMembershipProvider class implement) the full range of functionality that is possible in ASP.NET membership providers, as defined in the MembershipProvider base class that is used by all ASP.NET membership providers. For example, the base ASP.NET membership class supports options to store passwords as clear text, encrypted, or using a one-way hash. WebSecurity and SimpleMembershipProvider implement only the hashing option, which is considered the most secure of these options. As a result, WebSecurity does not let you recover a user’s password; instead, WebSecurity limits your password recovery option to letting you create a new password for the user.

The WebSecurity class does not include functionality for creating roles and assigning users to roles. For information about how to work with roles, see the SimpleRoleProvider class.

Information about membership is stored in a database. The membership system (SimpleMembershipProvider) can automatically create the database tables it requires. (The database itself must already exist.) It does this the first time that you initialize the membership system by calling Initialize(String, NameValueCollection), typically in your _AppStart.cshtml or _AppStart.vbhtml file.

By default, WebSecurity uses a simplified membership database schema compared with what ASP.NET membership can support. The design was implemented for several reasons. One is that the SimpleMembershipProvider class does not implement all ASP.NET membership functionality, therefore does not have to track as much information. Another reason is that the simplified schema is more user friendly, which makes it easier to work with if you ever have to query the database directly. Finally, the simplified schema was designed specifically to make it easier to integrate membership with existing database tables that already contain user names and email addresses.

Internally, information about individual users is stored in two types of tables: a user profile table and a membership table. The user profile table stores personal information about the user, such as the user's name and email address. The membership table stores user account information, such as the password, the date that the account was created, the last time that a login attempt failed, and so on. Dividing user information in this manner lets WebSecurity (and the membership system that WebSecurity is based on) keep the information for membership and security (like passwords) separate from user information.

Dividing the information into profile data and account data also makes it possible to integrate with existing user data. For example, you might already have a database table that contains employee information. In that case, the membership system can use its own membership table for account information (such as passwords) and use your employee table to get the user's name and other information, such as email address. The only requirement is that the user profile table must have a primary key that is typed as an integer, and it must contain a column for the user name. When you initialize the membership system, you can specify the database and table information for an existing user profile table and the membership system attaches to the existing profile table. If you do not already have a user profile table, the initialization method can create one for you.

NoteNote:

If you do not want to use the WebSecurity class for your site, you must configure your site to use the standard ASP.NET membership and role providers. In addition, you must not call the InitializeDatabaseConnection() method. The SimpleMembershipProvider and SimpleRoleProvider classes will still be loaded, but will pass method and property calls through to the standard membership and role providers.

For more information, see the SimpleMembershipProvider and SimpleRoleProvider class overviews.

The following example shows how to accept a user name and password in an ASP.NET Web Pages page, how to verify that the user exists in the membership table by using the UserExists(String) method, and how to log the user in by using the Login(String, String, Boolean) method.


@{
    // Initialize variables used in the login procedure.
    var username = "";
    var password = "";

    if (IsPost) {
        // Extract the data from the form.
        username = Request.Form["username"];
        password = Request.Form["password"];

        // Attempt to login the user.
        if (WebSecurity.Login(username, password)) {
            // Greet the user.
            <p>Welcome @username.</p>
            <p>Click <a href="MemberContent.cshtml">here</a> to continue.</p>
        } else {
            // Login failed.
            <p>Incorrect username or password.</p>
        }
        return;
    }
}

<form method="post" action="">
    <p>Log in to this Website:</p>
    <p>Username: <input type="text" name="username" /></p>
    <p>Password: <input type="password" name="password" /></p>
    <p><input type="submit" value="Submit" /></p>
</form>


The following example shows how to use the IsAuthenticated property in a page to display public and members-only content.


@{
    <p>Public content goes here.</p>

    if (!WebSecurity.IsAuthenticated)
    {
        // If this page is accessed before the user logs in, notify the user.
        <p>You must first log in to access the rest of this page.</p>
        <p>Click <a href="WebSecurityLogin.cshtml">here</a> to log in.</p>
        return;
    }
}

<p>Member-specific content goes here.</p>


Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.
Show:
© 2014 Microsoft