Presentation is loading. Please wait.

Presentation is loading. Please wait.

ASP.NET 2.0: A Look Inside Membership, Role Management, and Profiles in ASP.NET 2.0 Sam Spencer Program Manager Microsoft – Web Platform & Tools DEV312.

Similar presentations


Presentation on theme: "ASP.NET 2.0: A Look Inside Membership, Role Management, and Profiles in ASP.NET 2.0 Sam Spencer Program Manager Microsoft – Web Platform & Tools DEV312."— Presentation transcript:

1 ASP.NET 2.0: A Look Inside Membership, Role Management, and Profiles in ASP.NET 2.0 Sam Spencer Program Manager Microsoft – Web Platform & Tools DEV312

2 Agenda Membership Service Login Controls Role Management Service Profile Service

3 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

4 Membership Schema Membership API Membership Data Controls LoginLoginLoginStatusLoginStatusLoginViewLoginView Other Membership Providers Providers Membership Providers MembershipMembershipMembershipUserMembershipUser SqlMembershipProviderSqlMembershipProvider OtherControlsOtherControls SQL Server Other Data Stores SQL Server Express

5 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

6 Key Membership Methods NameDescription CreateUser Adds a user to the membership data store DeleteUser Removes a user from the membership data store GeneratePassword Generates a random password of a specified length GetAllUsers Retrieves a collection of MembershipUser objects representing all currently registered users GetUser Retrieves a MembershipUser object representing a user UpdateUser Updates information for a specified user ValidateUser Validates logins based on user names and passwords

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

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

9 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

10 Key MembershipUser Properties NameDescription Comment Storage for user-defined data CreationDate Date user was added to the membership data store Email User's e-mail address LastLoginDate Date user last logged in successfully LastPassword- ChangedDate Date user's password was last changed ProviderUserKey Unique user ID generated by membership provider UserName User's registered user name

11 Key MembershipUser Methods NameDescription ChangePassword Changes user's password ChangePassword- QuestionAndAnswer Changes question and answer used for password recovery GetPassword* Retrieves a password ResetPassword** Resets a password by setting it to a new random password UnlockUser Restores suspended login privileges * Works if Membership.EnablePasswordRetrieval is true ** Works if Membership.EnablePasswordReset is true Key MembershipUser Methods

12 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 }

13 Aspnet_regsql.exe Tool for creating database used by SqlMembershipProvider and other SQL Server providers

14 Configuring the Membership Service <membership defaultProvider="AspNetSqlMembershipProvider" userIsOnlineTimeWindow = "00:15:00" hashAlgorithmType = "[SHA1|MD5]" >...

15 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

16 Configuring SqlMembershipProvider <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,..." />

17 Membership

18 Login Controls NameDescription ChangePassword UI for changing passwords CreateUserWizard UI for creating new user accounts Login UI for entering and validating user names and passwords LoginName Displays authenticated user names LoginStatus UI for logging in and logging out LoginView Displays different views based on login status and roles PasswordRecovery UI for recovering forgotten passwords

19 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

20 Using the Login Control

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

22 Login Control Events NameDescription LoggingIn Fired when the user clicks the Log In button. Purpose: to Prevalidate login credentials (e.g., make sure e-mail address is well-formed) Authenticate Fired when the user clicks the Log In button. Purpose: to Authenticate the user by validating his or her login credentials LoggedIn Fired following a successful login LoginError Fired when an attempted login fails

23 Validating Credential Formats <asp:Login ID="LoginControl" RunAt="server" OnLoggingIn="OnValidateCredentials"... />. 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; }

24 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 Template-driven<AnonymousTemplate><LoggedInTemplate> and and

25 Using LoginView...

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

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

28 LoginStatus Properties NameDescription LoginText Text displayed for login link (default="Login") LogoutText Text displayed for logout link (default="Logout") LoginImageUrl URL of image used for login link LogoutAction Action to take following logout: Redirect, RedirectToLoginPage, or Refresh (default) LogOutPageUrl URL of page to go to following logout if LogoutAction="Redirect"

29 Login Controls

30 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

31 Role Management Schema Roles API Roles Data SQL Server Other Data Stores Controls LoginLoginLoginStatusLoginStatusLoginViewLoginView Other Role Providers Role Providers RolesRoles SqlRoleProviderSqlRoleProvider SQL Server Express OtherControlsOtherControls

32 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

33 Key Roles Methods NameDescription AddUserToRole Adds a user to a role CreateRole Creates a new role DeleteRole Deletes an existing role GetRulesForUser Gets a collection of roles to which a user belongs GetUsersInRole Gets a collection of users belonging to a specified role IsUserInRole Indicates whether a user belongs to a specified role RemoveUserFromRole Removes a user from the specified role

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

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

36 Enabling the Role Manager Role manager is disabled by default Enable it via Web.config:

37 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" >...

38 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

39 Configuring SqlRoleProvider <add applicationName="/" connectionStringName="LocalSqlServer" name="AspNetSqlRoleProvider" type="System.Web.Security.SqlRoleProvider, System.Web,..." />

40 Role Management

41 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

42 Profile Schema Profiles Profile Data Stores SQL Server Express Other Data Stores ProfileBaseProfileBase ProfileCommon (Autogenerated ProfileBase-Derivative) ProfileCommon Other Profile Providers Providers Profile Providers SqlProfileProviderSqlProfileProvider SQL Server

43 Defining a Profile

44 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;

45 How Profiles Work public partial class _Default : System.Web.SessionState.IRequiresSessionState {... protected ProfileCommon Profile { get { return ((ProfileCommon)(this.Context.Profile)); } }... } Autogenerated class representing the page Autogenerated class derived from ProfileBase containing properties Profile property included in autogenerated page class

46 Profile Groups Properties can be grouped element defines groups element defines groups Groups can’t be nested......

47 Defining a Profile Group

48 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;

49 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

50 Using a Custom Data Type Type nameUse binary serializer

51 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;

52 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"];

53 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

54 Profiles for Anonymous Users

55 Anonymous 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 cookied or cookieless (URL munging)

56 Global.asax Handler Name Description AnonymousIdentification_ Creating Called when anonymous ID is issued Profile_MigrateAnonymous Called when anonymous user is authenticated to allow migration of profile properties Profile_Personalize Called before profile is loaded to allow loading of custom profiles Profile_ProfileAutoSaving Called before profile is persisted to allow customization for profiles containing custom types Profile Events Profile service and anonymous identification service fire global events

57 Migrating Anonymous Users void Profile_MigrateAnonymous (Object sender, ProfileMigrateEventArgs e) { if (Profile.ScreenName == null) Profile.ScreenName = Profile.GetProfile (e.AnonymousId).ScreenName; } Global.asax

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

59 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

60 Configuring SqlProfileProvider <add applicationName="/" connectionStringName="LocalSqlServer" name="AspNetSqlRoleProvider" type="System.Web.Security.SqlProfileProvider, System.Web,..." />

61 Profiles

62 Resources Provider toolkit: http://msdn.microsoft.com/asp.net/beta2/providers/default.aspx ASP.NET 2.0 membership, login controls, and role management (webinar): http://www.microsoft.com/seminar/shared/asp/view.asp?url=/se minar/en/20050201_security/manifest.xml&rate=1 http://www.microsoft.com/seminar/shared/asp/view.asp?url=/se minar/en/20050201_security/manifest.xml&rate=1 ASP.NET 2.0 state management, including profiles (webinar): http://www.microsoft.com/seminar/shared/asp/view.asp?url=/se minar/en/20050201_statemanagement /manifest.xml&rate=1 http://www.microsoft.com/seminar/shared/asp/view.asp?url=/se minar/en/20050201_statemanagement /manifest.xml&rate=1

63 Get a 48% Discount on MSDN Universal Now! For a limited time purchase a 12 month MSDN Universal Subscription for $3565+GST (RRP). You will receive updates as they are released for SQL Server, BizTalk Server, Visual Studio, Exchange Server and Windows Server. You will also receive early access to beta products such as Windows Vista and Office 12. Get in now so that when Visual Studio Team System ships you will be upgraded at no cost to one of the new top tier subscriptions: Visual Studio 2005 Team Edition for Software Developers Visual Studio 2005 Team Edition for Software Architects Visual Studio 2005 Team Edition for Software Testers For more details and to find your local reseller visit: www.microsoft.co.nz/buyMSDN www.microsoft.co.nz/buyMSDN

64 We invite you to participate in our online evaluation on CommNet, accessible Friday only If you choose to complete the evaluation online, there is no need to complete the paper evaluation Your Feedback is Important!

65

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

67


Download ppt "ASP.NET 2.0: A Look Inside Membership, Role Management, and Profiles in ASP.NET 2.0 Sam Spencer Program Manager Microsoft – Web Platform & Tools DEV312."

Similar presentations


Ads by Google