WEB321 ASP.NET 2.0: A Look Inside Membership, Role Management, and Profiles in ASP.NET 2.

Jeff Prosise Cofounder Wintellect www.wintellect.com

Membership Service Login Controls Role Management Service Profile Service

Membership Service
Manages users and credentials
Declarative access via WS Admin Tool Programmatic access via Membership API

Simplifies forms authentication
Provides logic for validating user names and passwords, creating users, and more Manages data store for credentials, e-mail addresses, and other membership data

Provider-based for flexible data storage

Membership Schema
Login LoginStatus LoginView Other Controls

Membership API
Membership MembershipUser

Membership Providers
SqlMembershipProvider Other Membership Providers

Membership Data
SQL Server

SQL Server Express

Other Data Stores

The Membership Class
Provides static methods for performing key membership tasks
Creating and deleting users Retrieving information about users Generating random passwords Validating logins

Includes read-only static properties for acquiring data about provider settings

Key Membership Methods
CreateUser DeleteUser GeneratePassword GetAllUsers GetUser UpdateUser ValidateUser

Adds a user to the membership data store Removes a user from the membership data store Generates a random password of a specified length Retrieves a collection of MembershipUser objects representing all currently registered users Retrieves a MembershipUser object representing a user Updates information for a specified user Validates logins based on user names and passwords

Creating New Users
try { Membership.CreateUser ("Jeff", "imbatman!", "jeff@microsoft.com"); } catch (MembershipCreateUserException e) { // Find out why CreateUser failed switch (e.StatusCode) { case MembershipCreateStatus.DuplicateUsername: ... case MembershipCreateStatus.DuplicateEmail: ... case MembershipCreateStatus.InvalidPassword: ... default: ... } }

Validating Logins
if (Membership.ValidateUser (UserName.Text, Password.Text)) FormsAuthentication.RedirectFromLoginPage (UserName.Text, RememberMe.Checked);

The MembershipUser Class
Represents individual users registered in the membership data store Includes numerous properties for getting and setting user info Includes methods for retrieving, changing, and resetting passwords Returned by Membership methods such as GetUser and CreateUser

Key MembershipUser Properties
Comment CreationDate Email LastLoginDate LastPasswordChangedDate ProviderUserKey UserName

Storage for user-defined data Date user was added to the membership data store User's e-mail address Date user last logged in successfully Date user's password was last changed Unique user ID generated by membership provider User's registered user name

Key MembershipUser Methods Key MembershipUser Methods
ChangePassword ChangePasswordQuestionAndAnswer GetPassword* ResetPassword** UnlockUser

Changes user's password Changes question and answer used for password recovery Retrieves a password Resets a password by setting it to a new random password Restores suspended login privileges

* Works if Membership.EnablePasswordRetrieval is true ** Works if Membership.EnablePasswordReset is true

Restoring Login Privileges
MembershipUser user = Membership.GetUser ("Jeff"); if (user != null) { if (user.IsLockedOut) { user.UnlockUser (); // TODO: Optionally use MembershipUser.ResetPassword // to reset Jeff's password } }

Tool for creating database used by SqlMembershipProvider and other SQL Server providers

Configuring the Membership Service

<membership defaultProvider="AspNetSqlMembershipProvider" userIsOnlineTimeWindow = "00:15:00" hashAlgorithmType = "[SHA1|MD5]" > <providers> ... </providers> </membership>

Membership Providers
Membership is provider-based
Provider provides interface between Membership service and data store

Ships with one membership provider
SqlMembershipProvider (SQL Server and SQL Server Express)

Use custom providers for other Membership data stores

Configuring SqlMembershipProvider
<membership defaultProvider="AspNetSqlMembershipProvider"> <providers> <add name="AspNetSqlMembershipProvider" connectionStringName="LocalSqlServer" enablePasswordRetrieval="[true|false]" enablePasswordReset="[true|false]" requiresQuestionAndAnswer="[true|false]" applicationName="/" requiresUniqueEmail="[true|false]" passwordFormat="[Clear|Encrypted|Hashed]" maxInvalidPasswordAttempts="5" passwordAttemptWindow="10" passwordStrengthRegularExpression="" minRequiredPasswordLength="7" minRequiredNonalphanumericCharacters="1" type="System.Web.Security.SqlMembershipProvider, System.Web, ..." /> </providers> </membership>


Login Controls
ChangePassword CreateUserWizard Login LoginName LoginStatus LoginView PasswordRecovery

UI for changing passwords UI for creating new user accounts UI for entering and validating user names and passwords Displays authenticated user names UI for logging in and logging out Displays different views based on login status and roles UI for recovering forgotten passwords

The Login Control
Standard UI for logging in users Integrates with Membership service
Calls ValidateUser automatically No-code validation and logins

Also works without Membership service Incorporates RequiredFieldValidators Highly customizable UI and behavior

Using the Login Control
<html> <body> <form runat="server"> <asp:Login RunAt="server" /> </form> </body> </html>

Customizing the Login Control
<asp:Login ID="LoginControl" RunAt="server" CreateUserText="Create new account" CreateUserUrl="CreateUser.aspx" DisplayRememberMe="false" PasswordRecoveryText="Forgotten your password?" PasswordRecoveryUrl="RecoverPassword.aspx" LoginButtonText="Do It!" TitleText="Please Log In" />

Login Control Events
Name Description
Fired when the user clicks the Log In button. Purpose: to Prevalidate login credentials (e.g., make sure e-mail address is well-formed)



Fired when the user clicks the Log In button. Purpose: to Authenticate the user by validating his or her login credentials Fired following a successful login Fired when an attempted login fails

LoggedIn LoginError

Validating Credential Formats

<asp:Login ID="LoginControl" RunAt="server" OnLoggingIn="OnValidateCredentials" ... /> . . . <script language="C#" runat="server"> void OnValidateCredentials (Object sender, CancelEventArgs e) { if (!Regex.IsMatch (LoginControl.UserName, "[a-zA-Z0-9]{6,}") || !Regex.IsMatch (LoginControl.Password, "[a-zA-Z0-9]{8,}")) { LoginControl.InstructionText = "User names and passwords " + "must contain letters and numbers only and must be at " + "least 6 and 8 characters long, respectively"; e.Cancel = true; } } </script>

The LoginView Control
Displays content differently to different users depending on:
Whether user is authenticated If user is authenticated, the role memberships he or she is assigned

<AnonymousTemplate> <LoggedInTemplate> <RoleGroups> and <ContentTemplate>

Using LoginView
<asp:LoginView ID="LoginView1" Runat="server"> <AnonymousTemplate> <!-- Content seen by unauthenticated users --> </AnonymousTemplate> <LoggedInTemplate> <!-- Content seen by authenticated users --> </LoggedInTemplate> <RoleGroups> <asp:RoleGroup Roles="Administrators"> <ContentTemplate> <!-- Content seen by authenticated users who are administrators --> </ContentTemplate> </asp:RoleGroup> ... </RoleGroups> </asp:LoginView>

The LoginName Control
Displays authenticated user names Use optional FormatString property to control format of output
<asp:LoginView ID="LoginView1" Runat="server"> <AnonymousTemplate> You are not logged in </AnonymousTemplate> <LoggedInTemplate> <asp:LoginName ID="LoginName1" Runat="server" FormatString="You are logged in as {0}" /> </LoggedInTemplate> </asp:LoginView>

The LoginStatus Control
Displays links for logging in and out
"Login" to unauthenticated users "Logout" to authenticated users

UI and logout behavior are customizable
<asp:LoginStatus ID="LoginStatus1" Runat="server" LogoutAction="Redirect" LogoutPageUrl="~/Default.aspx" />

LoginStatus Properties
LognText LogoutText LoginImageUrl

Text displayed for login link (default="Login") Text displayed for logout link (default="Logout") URL of image used for login link Action to take following logout: Redirect, RedirectToLoginPage, or Refresh (default)



URL of page to go to following logout if LogoutAction="Redirect"

Login Controls

Role Management Service
Role-based security in a box
Declarative access via WS Admin Tool Programmatic access via Roles API

Simplifies adding role-based security to sites that employ forms authentication
Maps users to roles on each request Provides data store for role information

Provider-based for flexible data storage

Role Management Schema
Login LoginStatus LoginView Other Controls

Roles API


Role Providers
SqlRoleProvider Other Role Providers

Roles Data
SQL Server SQL Server Express Other Data Stores

The Roles Class
Gateway to the Role Management API Provides static methods for performing key role management tasks
Creating and deleting roles Adding users to roles Removing users from roles and more

Includes read-only static properties for acquiring data about provider settings

Key Roles Methods
AddUserToRole CreateRole DeleteRole GetRulesForUser GetUsersInRole IsUserInRole RemoveUserFromRole

Adds a user to a role Creates a new role Deletes an existing role Gets a collection of roles to which a user belongs Gets a collection of users belonging to a specified role Indicates whether a user belongs to a specified role Removes a user from the specified role

Creating a New Role
if (!Roles.RoleExists ("Developers")) { Roles.CreateRole ("Developers"); }

Adding a User to a Role
string name = Membership.GetUser ().Username; // Get current user Roles.AddUserToRole (name, "Developers"); // Add current user to role

Enabling the Role Manager
Role manager is disabled by default Enable it via Web.config:
<configuration> <system.web> <roleManager enabled="true" /> </system.web> </configuration>

Configuring the Role Manager
<roleManager enabled="[true|false]" defaultProvider="AspNetSqlRoleProvider" createPersistentCookie="[true|false]" cacheRolesInCookie="[true|false]" cookieName=".ASPXROLES" cookieTimeout="00:30:00" cookiePath="/" cookieRequireSSL="[true|false]" cookieSlidingExpiration="[true|true]" cookieProtection="[None|Validation|Encryption|All]" domain="" maxCachedResults="25" > <providers> ... </providers> </roleManager>

Role Management Providers
Role management is provider-based Ships with three role providers:
AuthorizationStoreRoleProvider (Authorization Manager, or "AzMan") SqlRoleProvider (SQL Server) WindowsTokenRoleProvider (Windows)

Use custom providers for other data stores

Configuring SqlRoleProvider

<roleManager defaultProvider="AspNetSqlRoleProvider" ...> <providers> <add applicationName="/" connectionStringName="LocalSqlServer" name="AspNetSqlRoleProvider" type="System.Web.Security.SqlRoleProvider, System.Web, ..." /> </providers> </roleManager>

Role Management

Profile Service
Stores per-user data persistently
Strongly typed (unlike session state) On-demand lookup (unlike session state) Long-lived (unlike session state) Supports authenticated and anonymous users

Accessed through dynamically compiled ProfileBase derivatives Provider-based for flexible data storage

Profile Schema
ProfileBase ProfileCommon (Autogenerated ProfileBase-Derivative)

Profile Providers
SqlProfileProvider Other Profile Providers

Profile Data Stores
SQL Server SQL Server Express Other Data Stores

Defining a Profile
<configuration> <system.web> <profile> <properties> <add name="ScreenName" /> <add name="Posts" type="System.Int32" defaultValue="0" /> <add name="LastPost" type="System.DateTime" /> </properties> </profile> </system.web> </configuration>

Using a Profile
// Increment the current user's post count Profile.Posts = Profile.Posts + 1; // Update the current user's last post date Profile.LastPost = DateTime.Now;

How Profiles Work
Autogenerated class representing the page
public partial class _Default : System.Web.SessionState.IRequiresSessionState { ... protected ProfileCommon Profile { get { return ((ProfileCommon)(this.Context.Profile)); } } ... }

Autogenerated class derived from ProfileBase containing <profile> properties

Profile property included in autogenerated page class

Profile Groups
Properties can be grouped <group> element defines groups Groups can’t be nested
<profile> <properties> <add ... /> ... <group name="..."> <add ... /> ... </group> </properties> </profile>

Defining a Profile Group
<configuration> <system.web> <profile> <properties> <add name="ScreenName" /> <group name="Forums"> <add name="Posts" type="System.Int32" defaultValue="0" /> <add name="LastPost" type="System.DateTime" /> </group> </properties> </profile> </system.web> </configuration>

Using a Profile Group
// Increment the current user's post count Profile.Forums.Posts = Profile.Forums.Posts + 1; // Update the current user's last post date Profile.Forums.LastPost = DateTime.Now;

Custom Data Types
Profiles support base types
String, Int32, Int64, DateTime, Decimal, etc.

Profiles also support custom types
Use type attribute to specify type Use serializeAs attribute to specify mode: Binary, Xml (default), or String

serializeAs="Binary" types must be serializable ([serializable] or ISerializable) serializeAs="String" types need type converters

Using a Custom Data Type
<configuration> <system.web> <profile> <properties> <add name="Cart" type="ShoppingCart" serializeAs="Binary" /> </properties> </profile> </system.web> </configuration>

Type name

Use binary serializer

Accessing Another Profile
Profile.propertyname refers to current user Use Profile.GetProfile (username) to access profiles for other users
// Get a reference to Fred's profile ProfileCommon profile = Profile.GetProfile ("Fred"); // Increment Fred's post count profile.Posts = profile.Posts + 1; // Update Fred's last post date profile.LastPost = DateTime.Now;

Accessing Profiles Externally
"Profile" property is only valid in classes generated by ASP.NET (ASPX, ASAX, etc.) Use HttpContext.Profile property to access profiles elsewhere (weak typing only)
// Read the current user's ScreenName property in an ASPX file string name = Profile.ScreenName; // Read the current user's ScreenName property in an external component string name = (string) HttpContext.Current.Profile["ScreenName"];

Anonymous User Profiles
By default, profiles aren’t available for anonymous (unauthenticated) users
Data keyed by authenticated user IDs

Anonymous profiles can be enabled
Step 1: Enable anonymous identification Step 2: Specify which profile properties are available to anonymous users

Data keyed by user anonymous IDs

Profiles for Anonymous Users

<configuration> <system.web> <anonymousIdentification enabled="true" /> <profile> <properties> <add name="ScreenName" allowAnonymous="true" /> <add name="Posts" type="System.Int32" defaultValue="0 /> <add name="LastPost" type="System.DateTime" /> </properties> </profile> </system.web> </configuration>

Anonymous Identification
Anonymous identification can be cookied or cookieless (URL munging)
<anonymousIdentification enabled="[true|false]" cookieName=".ASPXANONYMOUS" cookieTimeout="69:10:40" cookiePath="/" cookieRequireSSL="[true|false]" cookieSlidingExpiration="[true|false]" cookieProtection="[None|Validation|Encryption|All]" cookieless="[UseUri|UseCookies|AutoDetect|UseDeviceProfile]" domain="" />

Profile Events
Profile service and anonymous identification service fire global events
Global.asax Handler Name Description

AnonymousIdentification_Cre Called when anonymous ID is issued ating Profile_MigrateAnonymous Profile_Personalize
Profile_ProfileAutoSaving Called when anonymous user is authenticated to allow migration of profile properties Called before profile is loaded to allow loading of custom profiles Called before profile is persisted to allow customization for profiles containing custom types

Migrating Anonymous Users

<script language="C#" runat="server"> void Profile_MigrateAnonymous (Object sender, ProfileMigrateEventArgs e) { if (Profile.ScreenName == null) Profile.ScreenName = Profile.GetProfile (e.AnonymousId).ScreenName; } </script>

Configuring the Profile Service

<profile enabled="[true|false]" defaultProvider="AspNetSqlProfileProvider" automaticSaveEnabled="[true|false]" inherits="" // base class for ProfileCommon (default=ProfileBase) > <providers> ... </providers> </profile>

Profile Providers
Profile service is provider-based Ships with one profile provider
SqlProfileProvider (SQL Server and SQL Server Express)

Use custom providers to add support for other data stores

Configuring SqlProfileProvider

<profile defaultProvider="AspNetSqlProfileProvider" ...> <providers> <add applicationName="/" connectionStringName="LocalSqlServer" name="AspNetSqlRoleProvider" type="System.Web.Security.SqlProfileProvider, System.Web, ..." /> </providers> </profile>



ASP.NET 2.0 membership, login controls, and role management (webinar): http://www.microsoft.com/seminar/shared/asp/ view.asp?url =/seminar/en/20050201_security/manifest.xml&rate

ASP.NET 2.0 statement management, including profiles (webinar): http://www.microsoft.com/seminar/shared/asp/view

Your Feedback is Important!
Please Fill Out a Survey for This Session on CommNet

© 2005 Microsoft Corporation. All rights reserved.
This presentation is for informational purposes only. Microsoft makes no warranties, express or implied, in this summary.