Using the Membership and Role Manager APIs
The Membership feature is built around two central classes: Membership and MembershipUser. The Membership
class provides methods for creating users (represented by the MembershipUser class), as well as common administrative methods
for managing users. The users that are created with the Membership class represent the authenticated identities for an
Common tasks that you perform with the Membership class include:
Once you have obtained a MembershipUser instance, the common tasks that you perform directly with the MembershipUser
- Creating a new MembershipUser
- Validating a username-password combination when a user attempts to log in. You can then use Forms Authentication to issue
a cookie indicating that a user has logged in to a site.
- Retrieving a MembershipUser instance
- Updating a MembershipUser instance
- Searching for users based on various search criteria
- Getting the count of authenticated users that are currently online
- Deleting users from the system when they are no longer needed
- Accessing the properties on the MembershipUser class in your application
- Retrieving a user's password (only if the Membership feature is configured to allow password retrieval)
- Changing a user's password or resetting a user's password
- Changing a user's password question and password answer (if the Membership feature has been configured to prompt a user
for a password question and answer prior to retrieving or updating a password).
- Unlocking a user that has been locked out due to bad passwords or bad password answers.
The central management class for Role Manager is the Roles class. The Roles class provides methods for creating roles
and assigning users to roles. It also provides common administrative methods for managing role information.
Common tasks that you perform with the Roles class include:
The Role Manager feature also includes an
- Creating a new role
- Deleting an existing role
- Assigning users to roles
- Removing users from roles
- Determining if a user is authorized to a specific role
- Searching for users in a specific role, as well as retrieving all users in a role
- Getting the role information for a specific user
HttpModule. This module is responsible for retrieving
role assignments for a user and storing this information inside of a RolePrincipal that is available on the
a page. The existence of a RolePrincipal on the
HttpContext allows you to secure pages and directories using the
<authorization> element. Depending on the role information stored in the RolePrincipal, a user
can be authorized for only specific pages and directories within a site.
The following samples demonstrate how to use the Membership API in an application.
Creating a New User
The following sample demonstrates how to create a new MembershipUser. This sample uses the
overload that returns a status parameter. Other overloads are available that throw exceptions as opposed to returning a status
code. Note that by default, the Membership feature requires passwords to be at least seven characters long, and the password
must contain at least one non-alphanumeric character.
VB Creating a User Using Membership
User Login and Accessing User Properties
The following sample demonstrates user login with the
Membership.ValidateUser method. It also demonstrates
how to use Forms Authentication with Membership when logging in a user. With the user account created in the
previous sample, enter your credentials on the login page. Once you are logged in you will be redirected to a page
Membership.GetUser to retrieve the MembershipUser instance corresponding to the
logged in user. Also notice that the page that displays user properties has been placed in a directory that only allows access
to authenticated users. Click the logout link at the bottom of the page to log yourself out.
VB Login and Viewing User Properties
Updating User Properties
Login again using the credentials that were created earlier. The page displays the user properties with the DetailsView control that is new in ASP.NET 2.0.
The DetailsView control communicates with a data source control. In this example, an ObjectDataSource control is used to retrieve the contents of a
MembershipUser instance. You can click on the Edit link at the bottom of the page to toggle the DetailsView into edit mode. Both the email
and comment for the MembershipUser can be changed. When you want to save the new values to the database, click on the Update link. Notice in the
code that the page implements the
ItemUpdating event that is raised by the ObjectDataSource. This is necessary because the MembershipUser
class does not have a parameter-less constructor, which is a requirement to use automatic two-way databinding with ObjectDataSource. Click the logout link at
the bottom of the page to log yourself out.
VB Updating User Properties
The Membership feature automatically tracks the number of bad password attempts that occur during login. It also tracks the number of bad password answers that are supplied
when either retrieving a password or attempting to reset a password. This sample demonstrates the automatic account lockout ability, as well as how to unlock a user
once the account is locked out. First create a new user account using the Creating a New User sample. Next, click on the button below to run
the Account Lockout sample. The login page displays the number of bad login attempts you will need to make in order to lock yourself out. On the login
page, use the first account you created, and intentionally enter a bad password. Continue to use a bad password for the number of times indicated on the login page.
Notice that after making the appropriate number of bad login attempts, if you then use the correct password, you still cannot login - this is
because the Membership feature automatically locked the account out after the appropriate number of bad login attempts occurred. In order to unlock the user account,
login with the second user account that you just created. The page that is displayed is very similar to the previous sample that displayed user properties. However,
this page allows you to enter an arbitrary username in the textbox at the bottom of the page. Enter the username for the locked out account into this textbox and hit
the Enter key. The DetailsView control will refresh and show the information for this user. Notice that the checkbox
IsLockedOut for the lockout status is checked. The
LastLockoutDate has also been updated to indicate when the user was locked out. Click the unlock button at the bottom of the page to unlock the currently
displayed user. This will call the
UnlockUser method on the MembershipUser instance, thus unlocking the user account. After unlocking the user,
IsLockedOut checkbox has been cleared, and the
LastLockoutDate property has been reset. Click the logout link at the bottom of the page.
Now attempt to login with the first user account. Notice that you can now login successfully again.
VB Account Lockout
Deleting a User
You can delete a user with the
Membership.DeleteUser method. The following sample demonstrates deleting the currently
logged in user and then logging the user out with Forms Authentication.
VB Deleting A User
The following samples demonstrate the Role Manager feature using roles with an authenticated user. All of the sample pages deny access to anonymous users.
If you have not already done so, create a new user with the Creating a New User sample. By default the Role Manager feature is
not enabled in ASP.NET. However, the web.config used in the following samples explicitly enables the Role Manager feature.
Adding and Deleting Roles
The following sample demonstrates how to create and delete roles using the
Roles.DeleteRole methods. After you create a new role, or delete an existing role, the page uses the
method to display the available roles in the system. The return value from
Roles.GetAllRoles can be easily bound to
any control that supports databinding. For the last sample, you will want to create at least one role called "Administrators".
As you create and delete roles, note that the Role Manager feature does not allow you to
create duplicate roles. Also note that, by default, Role Manager does not allow you to delete populated roles.
VB Adding And Deleting Roles
Adding a User to a Role and Deleting a User from a Role
Using the roles that you previously created, this sample demonstrates how to add a user to a role and how to remove a user from a role.
A user is added to a role with the
Roles.AddUserToRole method, while a user is removed from a role with the
Roles.RemoveUserFromRole method. Prior to adding a user to a role, a check is made to ensure that the user is not
already a member of the role. This check is performed because Role Manager throws an exception if you attempt to add a user more
than once to a role. As with the previous sample, role information and role membership is displayed using data-bound controls. The
list of roles that a user belongs to is retrieved with the
Roles.GetRolesForUser method. For the next sample to
work, make sure to add yourself to the "Administrators" role.
VB Adding And Deleting Users To/From Roles
Authorizing Access to a Page with Role Manager
The web.config file for this sample contains an
<authorization> element restricting access to members of the
"Administrators" role. If you have not already done so, make sure to create a role called "Administrators" and add yourself to that
role. Once you are a member of the "Administrators" role, you will be able to reach the sample page. ASP.NET provides a Role
HttpModule that automatically attaches a RolePrincipal to the
HttpContext of the current request. If you are a
member of the "Administrators" role, when Url authorization performs an
IsInRole check against the RolePrincipal
(Url authorization calls
RolePrincipal.IsInRole), the access check returns
true and you are allowed
to access the page. Note that you can reference a RolePrincipal in your page by calling
Page.User and casting
the result to a RolePrincipal.
VB Authorizing Access To a Page For A Role
Programmatically Checking Authorization
Because the Role Manager feature attaches a RolePrincipal to the
HttpContext, you can also write code to perform access checks against the
RolePrincipal. If you have not already done so, make sure to create two additional roles called "Regular Users" and "Power Users". Add yourself to these
roles as well. When you run the sample, the page performs
IsInRole checks using a variety of techniques. Some access checks are made using
User.IsInRole. This demonstrates that the RolePrincipal is available using the normal
Page.User syntax. The page also demonstrates
Page.User to a RolePrincipal reference, and then calling
IsInRole directly on the RolePrincipal.
VB Programmtic Authorization