65
WEB321 WEB321 ASP.NET 2.0: A Look Inside ASP.NET 2.0: A Look Inside Membership, Role Membership, Role Management, and Profiles in Management, and Profiles in ASP.NET 2.0 ASP.NET 2.0 Jeff Prosise Jeff Prosise Cofounder Cofounder Wintellect Wintellect www.wintellect.com www.wintellect.com

WEB321 ASP.NET 2.0: A Look Inside Membership, Role Management, and Profiles in ASP.NET 2.0 Jeff Prosise Cofounder Wintellect

Embed Size (px)

Citation preview

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

Jeff ProsiseJeff ProsiseCofounderCofounderWintellect Wintellect www.wintellect.comwww.wintellect.com

AgendaAgenda

Membership ServiceMembership Service

Login ControlsLogin Controls

Role Management ServiceRole Management Service

Profile ServiceProfile Service

Membership ServiceMembership Service

Manages users and credentialsManages users and credentialsDeclarative access via WS Admin ToolDeclarative access via WS Admin Tool

Programmatic access via Membership APIProgrammatic access via Membership API

Simplifies forms authenticationSimplifies forms authenticationProvides logic for validating user names Provides logic for validating user names and passwords, creating users, and moreand passwords, creating users, and more

Manages data store for credentials, e-mail Manages data store for credentials, e-mail addresses, and other membership dataaddresses, and other membership data

Provider-based for flexible data storageProvider-based for flexible data storage

Membership SchemaMembership Schema

Membership API

MembershipData

ControlsLoginLoginLoginLogin LoginStatusLoginStatusLoginStatusLoginStatus LoginViewLoginViewLoginViewLoginView

Other MembershipOther MembershipProvidersProviders

Other MembershipOther MembershipProvidersProviders

Membership Providers

MembershipMembershipMembershipMembership MembershipUserMembershipUserMembershipUserMembershipUser

SqlMembershipProviderSqlMembershipProviderSqlMembershipProviderSqlMembershipProvider

OtherOtherControlsControlsOtherOther

ControlsControls

SQL ServerSQL Server OtherOtherData StoresData Stores

SQL ServerSQL ServerExpressExpress

The Membership ClassThe Membership Class

Provides static methods for performing Provides static methods for performing key membership taskskey membership tasks

Creating and deleting usersCreating and deleting users

Retrieving information about usersRetrieving information about users

Generating random passwordsGenerating random passwords

Validating loginsValidating logins

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

Key Membership MethodsKey Membership Methods

NameName DescriptionDescription

CreateUserCreateUser Adds a user to the membership data storeAdds a user to the membership data store

DeleteUserDeleteUser Removes a user from the membership data storeRemoves a user from the membership data store

GeneratePasswordGeneratePassword Generates a random password of a specified lengthGenerates a random password of a specified length

GetAllUsersGetAllUsers Retrieves a collection of MembershipUser objects Retrieves a collection of MembershipUser objects representing all currently registered usersrepresenting all currently registered users

GetUserGetUser Retrieves a MembershipUser object representing a userRetrieves a MembershipUser object representing a user

UpdateUserUpdateUser Updates information for a specified userUpdates information for a specified user

ValidateUserValidateUser Validates logins based on user names and passwordsValidates logins based on user names and passwords

Creating New UsersCreating New Users

try { Membership.CreateUser ("Jeff", "imbatman!", "[email protected]");}catch (MembershipCreateUserException e) { // Find out why CreateUser failed switch (e.StatusCode) {

case MembershipCreateStatus.DuplicateUsername: ... case MembershipCreateStatus.DuplicateEmail: ... case MembershipCreateStatus.InvalidPassword: ... default: ... }}

Validating LoginsValidating Logins

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

The MembershipUser ClassThe MembershipUser Class

Represents individual users registered Represents individual users registered in the membership data storein the membership data store

Includes numerous properties for Includes numerous properties for getting and setting user infogetting and setting user info

Includes methods for retrieving, Includes methods for retrieving, changing, and resetting passwordschanging, and resetting passwords

Returned by Membership methods Returned by Membership methods such as GetUser and CreateUsersuch as GetUser and CreateUser

Key MembershipUser PropertiesKey MembershipUser Properties

NameName DescriptionDescription

CommentComment Storage for user-defined data

CreationDateCreationDate Date user was added to the membership data store

EmailEmail User's e-mail address

LastLoginDateLastLoginDate Date user last logged in successfully

LastPassword-LastPassword-ChangedDateChangedDate Date user's password was last changed

ProviderUserKeyProviderUserKey Unique user ID generated by membership provider

UserNameUserName User's registered user name

Key MembershipUser MethodsKey MembershipUser Methods

NameName DescriptionDescription

ChangePasswordChangePassword Changes user's password

ChangePassword-ChangePassword-QuestionAndAnswerQuestionAndAnswer

Changes question and answer used for password

recovery

GetPassword*GetPassword* Retrieves a password

ResetPassword**ResetPassword** Resets a password by setting it to a new random password

UnlockUserUnlockUser Restores suspended login privileges

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

Key MembershipUser MethodsKey MembershipUser Methods

Restoring Login PrivilegesRestoring 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

}}

Aspnet_regsql.exeAspnet_regsql.exe

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

Configuring the Membership ServiceConfiguring the Membership Service

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

Membership ProvidersMembership Providers

Membership is provider-basedMembership is provider-basedProvider provides interface between Provider provides interface between Membership service and data storeMembership service and data store

Ships with one membership providerShips with one membership providerSqlMembershipProvider (SQL Server and SqlMembershipProvider (SQL Server and SQL Server Express)SQL Server Express)

Use custom providers for other Use custom providers for other Membership data storesMembership data stores

Configuring SqlMembershipProviderConfiguring 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>

MembershipMembership

Login ControlsLogin Controls

NameName DescriptionDescription

ChangePasswordChangePassword UI for changing passwords

CreateUserWizardCreateUserWizard UI for creating new user accounts

LoginLogin UI for entering and validating user names and passwords

LoginNameLoginName Displays authenticated user names

LoginStatusLoginStatus UI for logging in and logging out

LoginViewLoginView Displays different views based on login status and roles

PasswordRecoveryPasswordRecovery UI for recovering forgotten passwords

The Login ControlThe Login Control

Standard UI for logging in usersStandard UI for logging in users

Integrates with Membership serviceIntegrates with Membership serviceCalls ValidateUser automaticallyCalls ValidateUser automatically

No-code validation and loginsNo-code validation and logins

Also works without Membership Also works without Membership serviceservice

Incorporates RequiredFieldValidatorsIncorporates RequiredFieldValidators

Highly customizable UI and behaviorHighly customizable UI and behavior

Using the Login ControlUsing the Login Control

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

Customizing the Login ControlCustomizing 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 EventsLogin Control Events

NameName DescriptionDescription

LoggingInLoggingInFired when the user clicks the Log In button. Purpose: to

Prevalidate login credentials (e.g., make sure e-mail

address is well-formed)

AuthenticateAuthenticateFired when the user clicks the Log In button. Purpose: to

Authenticate the user by validating his or her

login credentials

LoggedInLoggedIn Fired following a successful login

LoginErrorLoginError Fired when an attempted login fails

Validating Credential FormatsValidating 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 ControlThe LoginView Control

Displays content differently to different Displays content differently to different users depending on:users depending on:

Whether user is authenticatedWhether user is authenticated

If user is authenticated, the role If user is authenticated, the role memberships he or she is assignedmemberships he or she is assigned

Template-drivenTemplate-driven<AnonymousTemplate><AnonymousTemplate>

<LoggedInTemplate><LoggedInTemplate>

<RoleGroups> and <ContentTemplate><RoleGroups> and <ContentTemplate>

Using LoginViewUsing 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 ControlThe LoginName Control

Displays authenticated user namesDisplays authenticated user names

Use optional FormatString property to Use optional FormatString property to control format of outputcontrol 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 ControlThe LoginStatus Control

Displays links for logging in and outDisplays links for logging in and out"Login" to unauthenticated users"Login" to unauthenticated users

"Logout" to authenticated users"Logout" to authenticated users

UI and logout behavior are UI and logout behavior are customizablecustomizable

<asp:LoginStatus ID="LoginStatus1" Runat="server" LogoutAction="Redirect" LogoutPageUrl="~/Default.aspx" />

LoginStatus PropertiesLoginStatus Properties

NameName DescriptionDescription

LognTextLognText Text displayed for login link (default="Login")

LogoutTextLogoutText Text displayed for logout link (default="Logout")

LoginImageUrlLoginImageUrl URL of image used for login link

LogoutActionLogoutActionAction to take following logout: Redirect,

RedirectToLoginPage, or Refresh (default)

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

Login ControlsLogin Controls

Role Management ServiceRole Management Service

Role-based security in a boxRole-based security in a boxDeclarative access via WS Admin ToolDeclarative access via WS Admin Tool

Programmatic access via Roles APIProgrammatic access via Roles API

Simplifies adding role-based security to Simplifies adding role-based security to sites that employ forms authenticationsites that employ forms authentication

Maps users to roles on each requestMaps users to roles on each request

Provides data store for role informationProvides data store for role information

Provider-based for flexible data storageProvider-based for flexible data storage

Role Management SchemaRole Management Schema

Roles API

Roles Data

SQL ServerSQL Server OtherOtherData StoresData Stores

ControlsLoginLoginLoginLogin LoginStatusLoginStatusLoginStatusLoginStatus LoginViewLoginViewLoginViewLoginView

Other Role ProvidersOther Role ProvidersOther Role ProvidersOther Role Providers

Role Providers

RolesRolesRolesRoles

SqlRoleProviderSqlRoleProviderSqlRoleProviderSqlRoleProvider

SQL ServerSQL ServerExpressExpress

OtherOtherControlsControlsOtherOther

ControlsControls

The Roles ClassThe Roles Class

Gateway to the Role Management APIGateway to the Role Management API

Provides static methods for performing Provides static methods for performing key role management taskskey role management tasks

Creating and deleting rolesCreating and deleting roles

Adding users to rolesAdding users to roles

Removing users from roles and moreRemoving users from roles and more

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

Key Roles MethodsKey Roles Methods

NameName DescriptionDescription

AddUserToRoleAddUserToRole Adds a user to a role

CreateRoleCreateRole Creates a new role

DeleteRoleDeleteRole Deletes an existing role

GetRulesForUserGetRulesForUser Gets a collection of roles to which a user belongs

GetUsersInRoleGetUsersInRole Gets a collection of users belonging to a specified role

IsUserInRoleIsUserInRole Indicates whether a user belongs to a specified role

RemoveUserFromRoleRemoveUserFromRole Removes a user from the specified role

Creating a New RoleCreating a New Role

if (!Roles.RoleExists ("Developers")) { Roles.CreateRole ("Developers");}

Adding a User to a RoleAdding a User to a Role

string name = Membership.GetUser ().Username; // Get current userRoles.AddUserToRole (name, "Developers"); // Add current user to role

Enabling the Role ManagerEnabling the Role Manager

Role manager is disabled by defaultRole manager is disabled by default

Enable it via Web.config:Enable it via Web.config:

<configuration> <system.web> <roleManager enabled="true" /> </system.web></configuration>

Configuring the Role ManagerConfiguring 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 ProvidersRole Management Providers

Role management is provider-basedRole management is provider-based

Ships with three role providers:Ships with three role providers:AuthorizationStoreRoleProvider AuthorizationStoreRoleProvider (Authorization Manager, or "AzMan")(Authorization Manager, or "AzMan")

SqlRoleProvider (SQL Server)SqlRoleProvider (SQL Server)

WindowsTokenRoleProvider (Windows)WindowsTokenRoleProvider (Windows)

Use custom providers for other Use custom providers for other data storesdata stores

Configuring SqlRoleProviderConfiguring SqlRoleProvider

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

Role ManagementRole Management

Profile ServiceProfile Service

Stores per-user data persistentlyStores per-user data persistentlyStrongly typed (unlike session state)Strongly typed (unlike session state)

On-demand lookup (unlike session state)On-demand lookup (unlike session state)

Long-lived (unlike session state)Long-lived (unlike session state)

Supports authenticated and anonymous Supports authenticated and anonymous usersusers

Accessed through dynamically Accessed through dynamically compiled ProfileBase derivativescompiled ProfileBase derivatives

Provider-based for flexible data storageProvider-based for flexible data storage

Profile SchemaProfile Schema

Profiles

Profile Data Stores

SQL ServerSQL ServerExpressExpress

OtherOtherData StoresData Stores

ProfileBaseProfileBaseProfileBaseProfileBase

ProfileCommonProfileCommon(Autogenerated ProfileBase-Derivative)(Autogenerated ProfileBase-Derivative)

ProfileCommonProfileCommon(Autogenerated ProfileBase-Derivative)(Autogenerated ProfileBase-Derivative)

Other ProfileOther ProfileProvidersProviders

Other ProfileOther ProfileProvidersProviders

Profile Providers

SqlProfileProviderSqlProfileProviderSqlProfileProviderSqlProfileProvider

SQL ServerSQL Server

Defining a ProfileDefining 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 ProfileUsing a Profile

// Increment the current user's post countProfile.Posts = Profile.Posts + 1;

// Update the current user's last post dateProfile.LastPost = DateTime.Now;

How Profiles WorkHow Profiles Work

public partial class _Default : System.Web.SessionState.IRequiresSessionState{ ... protected ProfileCommon Profile { get { return ((ProfileCommon)(this.Context.Profile)); } } ...}

Autogenerated classrepresenting the page

Autogenerated class derived from ProfileBase containing<profile> properties

Profile property included inautogenerated page class

Profile GroupsProfile Groups

Properties can be groupedProperties can be grouped

<group> element defines groups<group> element defines groups

Groups can’t be nestedGroups can’t be nested

<profile> <properties> <add ... /> ... <group name="..."> <add ... /> ... </group> </properties></profile>

Defining a Profile GroupDefining 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 GroupUsing a Profile Group

// Increment the current user's post countProfile.Forums.Posts = Profile.Forums.Posts + 1;

// Update the current user's last post dateProfile.Forums.LastPost = DateTime.Now;

Custom Data TypesCustom Data Types

Profiles support base typesProfiles support base typesString, Int32, Int64, DateTime, Decimal, etc.String, Int32, Int64, DateTime, Decimal, etc.

Profiles also support custom typesProfiles also support custom typesUse type attribute to specify typeUse type attribute to specify type

Use serializeAs attribute to specify mode: Binary, Use serializeAs attribute to specify mode: Binary, Xml (default), or StringXml (default), or String

serializeAs="Binary" types must be serializeAs="Binary" types must be serializable ([serializable] or ISerializable)serializable ([serializable] or ISerializable)

serializeAs="String" types need type serializeAs="String" types need type convertersconverters

Using a Custom Data TypeUsing 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 ProfileAccessing Another Profile

Profile.propertyname refers to Profile.propertyname refers to current usercurrent user

Use Profile.GetProfile (username) to Use Profile.GetProfile (username) to access profiles for other usersaccess profiles for other users

// Get a reference to Fred's profileProfileCommon profile = Profile.GetProfile ("Fred");

// Increment Fred's post countprofile.Posts = profile.Posts + 1;

// Update Fred's last post dateprofile.LastPost = DateTime.Now;

Accessing Profiles ExternallyAccessing Profiles Externally

"Profile" property is only valid in "Profile" property is only valid in classes generated by ASP.NET (ASPX, classes generated by ASP.NET (ASPX, ASAX, etc.)ASAX, etc.)

Use HttpContext.Profile property to Use HttpContext.Profile property to access profiles elsewhere access profiles elsewhere (weak typing only)(weak typing only)

// Read the current user's ScreenName property in an ASPX filestring name = Profile.ScreenName;

// Read the current user's ScreenName property in an external componentstring name = (string) HttpContext.Current.Profile["ScreenName"];

Anonymous User ProfilesAnonymous User Profiles

By default, profiles aren’t available for By default, profiles aren’t available for anonymous (unauthenticated) usersanonymous (unauthenticated) users

Data keyed by authenticated user IDsData keyed by authenticated user IDs

Anonymous profiles can be enabledAnonymous profiles can be enabledStep 1: Enable anonymous identificationStep 1: Enable anonymous identification

Step 2: Specify which profile properties Step 2: Specify which profile properties are available to anonymous usersare available to anonymous users

Data keyed by user anonymous IDsData keyed by user anonymous IDs

Profiles for Anonymous UsersProfiles 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 IdentificationAnonymous Identification

<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=""/>

Anonymous identification can be Anonymous identification can be cookied or cookieless (URL munging)cookied or cookieless (URL munging)

Global.asax Handler Global.asax Handler NameName DescriptionDescription

AnonymousIdentification_Creating

Called when anonymous ID is issued

Profile_MigrateAnonymousCalled when anonymous user is authenticated

to allow migration of profile properties

Profile_PersonalizeCalled before profile is loaded to allow loading

of custom profiles

Profile_ProfileAutoSavingCalled before profile is persisted to allow

customization for profiles containing custom types

Profile EventsProfile Events

Profile service and anonymous Profile service and anonymous identification service fire global eventsidentification service fire global events

Migrating Anonymous UsersMigrating 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>

Global.asax

Configuring the Profile ServiceConfiguring the Profile Service

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

Profile ProvidersProfile Providers

Profile service is provider-basedProfile service is provider-based

Ships with one profile providerShips with one profile providerSqlProfileProvider (SQL Server and SQL SqlProfileProvider (SQL Server and SQL Server Express)Server Express)

Use custom providers to add support Use custom providers to add support for other data storesfor other data stores

Configuring SqlProfileProviderConfiguring SqlProfileProvider

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

ProfilesProfiles

Your FeedbackYour Feedbackis Important!is Important!Please Fill Out a Survey forPlease Fill Out a Survey forThis Session on CommNetThis 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.