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
65
Embed
WEB321 ASP.NET 2.0: A Look Inside Membership, Role Management, and Profiles in ASP.NET 2.0 Jeff Prosise Cofounder Wintellect .
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
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
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
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
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
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 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
<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
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
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:
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")
// 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
"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
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
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=1
ASP.NET 2.0 statement management, including profiles (webinar):http://www.microsoft.com/seminar/shared/asp/view.asp?url=/seminar/en/20050201_statemanagement/manifest.xml&rate=1
Your FeedbackYour Feedbackis Important!is Important!Please Fill Out a Survey forPlease Fill Out a Survey forThis Session on CommNetThis Session on CommNet