Accessing the Membership and Roles Features in Code


The membership and roles system is implemented through a series of classes within the .NET Framework, and you can access these classes to read and set properties, and to call methods, in your code if you need to bypass or complement the built-in membership and role features of ASP.NET. The following are the three main classes:

  • Membership

  • MembershipUser

  • Roles

We will briefly look at the members of each class to give you an idea of the kind of things you can accomplish in your code.

The Membership Class

The Membership class exposes a set of static properties that refer to the currently logged in user. The properties equate to those you saw in machine.config that control how the membership system behaves. It includes properties such as EnablePasswordReset, EnablePassword Retrieval, MinRequiredPasswordLength, and RequiresQuestionAnd Answer.

The Membership Methods

There is a range of methods that allow you to get information about and manipulate the current user, and to find and get information about other users.

Create and Delete a User

You can create and delete users with CreateUser and DeleteUser methods, which provide several overloads. These are the most commonly used:

Membership.CreateUser(user-name, password) Membership.CreateUser(user-name, password, email) Membership.DeleteUser(name)


Get a Reference to a User

You can get a reference to a single user as a MembershipUser instance using one of the overloads of the GetUser method. Setting the is-online parameter to true means that the LastActivity property is updated in the membership system as well:

MembershipUser thisUser = Membership.GetUser() MembershipUser thisUser = Membership.GetUser(user-name) MembershipUser thisUser = Membership.GetUser(is-online) MembershipUser thisUser = Membership.GetUser(user-name, is-online)


Find or Get a List of Users

To find users by name or e-mail address, or to get a list of all users, you use one of the following methods. All return a MembershipUser Collection instance, which you can iterate through to get a reference to each MembershipUser instance, or bind directly to a list control to display the user details.

MembershipUserCollection list = Membership.FindUsersByName(user-name) MembershipUserCollection list = Membership.FindUsersByEmail(email) MembershipUserCollection list = Membership.GetAllUsers()


Get the User Name from an E-mail Address

You can also get the name of a user directly if you know the user's email address:

String user-name = Membership.GetUserNameByEmail(email)


Determine the Number of Users Online

If you want to know how many users are online, you can call the following method:

Int32 count = Membership.GetNumberOfUsersOnline()


The Membership Event

There is one event raised by the Membership class that occurs when the current user account is created or the user's password is changed or reset. The ValidatingPassword event passes to its event handler an instance of the ValidatePasswordEventArgs class, which exposes properties that indicate the user name, the new password, whether this is a new user account, information on why the update failed if it did, and a Cancel parameter that you can set to TRue to prevent the update taking place.

Validating a User

As a simple example of using the Membership class, the code fragment shown in Listing 11.13 checks if the user name and password are valid, and if so calls the RedirectFromLoginPage method of the FormsAuthentication class to redirect the user to the next page. If authentication fails, the code displays a message.

A full list of the properties and methods of the Membership class is available at http://msdn2.microsoft.com/library/system.web.security.membership_members.

For details of the FormsAuthentication class, see http://msdn2.microsoft.com/library/k3fc21xw(en-US,VS.80).aspx.


Listing 11.13. A Simple Example of Validating a User in Code

if (Membership.ValidateUser(user-name, password)) {   FormsAuthentication.RedirectFromLoginPage(user-name, false); } else {   MyLabel.Text = "Authentication failed"; }

The MembershipUser Class

The MembershipUser class represents a single user within the ASP.NET membership system, obtained from one of the Find or Get methods of the Membership class. It exposes properties that you can read or set to update this user. The property names are self-explanatory, and include LastLogin Date, CreationDate, LastActivityDate, LastPasswordChangedDate, Email, IsApproved, PasswordQuestion, and UserName.

After you update any of these properties, you must call the static UpdateUser method of the Membership class to push the changes back into the membership system. This approach means that updating several properties only requires one call to the database to perform the update.

Membership.UpdateUser(this-user)


The MembershipUser Methods

The following methods are available.

Get Password

To get the password for a user, so that you can perform custom validation, use one of the overloads of the GetPassword methoddepending on whether the membership system is configured to require users to provide a security question and answer:

String password = this-user.GetPassword() String password = this-user.GetPassword(answer)


Change Password

To change the password of a user, call the ChangePassword method:

Boolean worked = this-user.ChangePassword(oldPassword, newPassword)


Change Security Q/A

There is also a method to change the security question and answer for a user:

Boolean worked = this-user.ChangePasswordQuestionAndAnswer(password,                                                    question, answer)


Reset Password

Finally, to reset the password when it cannot be retrieved (when EnablePasswordReset is true and EnablePasswordRetrieval is false) use the ResetPassword method. This returns the newly generated random password:

String newPassword = this-user.ResetPassword() String newPassword = this-user.ResetPassword(answer)


A full list of the properties and methods of the MembershipUser class is available at http://msdn2.microsoft.com/library/system.web.security.membershipuser_members.


The Roles Class

The Roles class provides methods that you can use to modify the roles in your application, get information about which users are in a role, add users to a role, and remove them from a role.

Create/Delete Roles

To create or delete roles, you use the CreateRole and DeleteRole methods:

Roles.CreateRole(role-name) Roles.DeleteRole(role-name)


Get Role Names Lists

You use several different methods and overloads to get lists of role names as a String array. If you do not specify a user name for the GetrolesForUser method, it assumes the current user:

String[] role-names = Roles.GetAllRoles() String[] role-names = Roles.GetRolesForUser() String[] role-names = Roles.GetRolesForUser(user-name) String[] user-names = Roles.GetUsersInRole(role-name) String[] user-names = Roles.FindUsersInRole(role-name, user-name)


Check if User Is in Role

To check if a user is in a role, you use the IsUserInRole method. Again, if you do not specify a user name, the method assumes the current user:

Boolean result = Roles.IsUserInRole(role-name) Boolean result = Roles.IsUserInRole(user-name, role-name)


Add Users to Roles

You can add users to roles with one of the overloads of the Add User(s)ToRole(s) methods. The relationship between users and roles is many-to-many, in that a user can be in more than one role, and a role contains more than one user. Therefore, there are methods that take single and an array of user names and/or role names:

Roles.AddUserToRole(user-name, role-name) Roles.AddUserToRoles(user-name, role-names[]) Roles.AddUsersToRole(user-names[], role-name) Roles.AddUsersToRoles(user-names[], role-names[])


Remove Users from Roles

To remove users from roles, you use one of the equivalent overloads of the RemoveUser(s)FromRole method:

Roles.RemoveUserFromRole(user-name, role-name) Roles.RemoveUserFromRoles(user-name, role-names[]) Roles.RemoveUsersFromRole(user-names[], role-name) Roles.RemoveUsersFromRoles(user-names[], role-names[])


A full list of the properties and methods of the Roles class is available at http://msdn2.microsoft.com/library/system.web.security.roles_members.




ASP. NET 2.0 Illustrated
ASP.NET 2.0 Illustrated
ISBN: 0321418344
EAN: 2147483647
Year: 2006
Pages: 147

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net