360 likes | 715 Views
Building Secure Applications using Membership and Role Management with Visual Studio 2005 and ASP.NET 2.0. Agenda. Membership Service. Membership Schema. Controls. Login. LoginStatus. LoginView. Other Login Controls. Membership API. Membership. MembershipUser. Membership Providers.
E N D
Building Secure Applications using Membership and Role Management with Visual Studio 2005 and ASP.NET 2.0
Membership Schema Controls Login LoginStatus LoginView Other Login Controls Membership API Membership MembershipUser Membership Providers SqlMembershipProvider Other Membership Providers Membership Data SQL Server Other Data Stores
Key Membership Methods Name Description 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
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);
Key MembershipUser Properties Name Description 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 LastPasswordChangedDate Date user's password was last changed UserId Unique user ID generated by membership provider UserName User's registered user name
Key MembershipUser Methods Name Description 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
Suspending Login Privileges if (Membership.ValidateUser (UserName.Text, Password.Text)) { MembershipUser user = Membership.GetUser (UserName.Text); user.Comment = "0"; // Reset the count of failed login attempts RedirectFromLoginPage (UserName.Text, RememberMe.Checked); } else { MembershipUser user = Membership.GetUser (UserName.Text); if (user != null) { // Get a count of consecutive failed login attempts string count = Convert.ToInt32 (user.Comment) + 1; // If the count equals or exceeds 5, suspend login privileges if (count >= 5) user.IsApproved = false; // Update the count of consecutive failed login attempts user.Comment = count.ToString (); } }
Changing Provider Settings <membership> <providers> <remove name="AspNetSqlProvider" /> <add name="AspNetSqlProvider" type="System.Web.Security.SqlMembershipProvider, System.Web, ..." connectionStringName="RemoteSqlServer" enablePasswordRetrieval="false" enablePasswordReset="true" requiresQuestionAndAnswer="false" applicationName="/" requiresUniqueEmail="false" passwordFormat="Hashed" description="Stores and retrieves membership data ..." /> </providers> </membership>
Login Controls Control Description 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
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" SubmitButtonText="Do It!" TitleText="Please Log In" />
Login Control Events Name Description 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 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) LoginError Fired when an attempted login fails
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>
Layout Templates <asp:Login RunAt="server"> <LayoutTemplate> ... </LayoutTemplate> </asp:Login>
Role Management Schema Controls Login LoginStatus LoginView Other Login Controls Roles API Roles Role Providers SqlRoleProvider Other Role Providers Roles Data SQL Server Other Data Stores
Key Roles Methods Name Description AddUserToRole Adds a user to a role CreateRole Creates a new role DeleteRole Deletes an existing role GetRolesForUser 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
Creating a New Role if (!Roles.RoleExists ("Developers")) { Roles.CreateRole ("Developers"); }
Adding a User to a Role string name = Membership.GetUser ().Username; Roles.AddUserToRole (name, "Developers");
Enabling the Role Manager <configuration> <system.web> <roleManager enabled="true" /> </system.web> </configuration>
Enabling Role Caching <configuration> <system.web> <roleManager enabled="true" cacheRolesInCookie="true" /> <!-- Other roleManager attributes (and their defaults) include: cookieName=".ASPXROLES" // Cookie name cookieTimeout="30" // Cookie lifetime cookiePath="/" // Cookie path cookieRequireSSL="false" // Restrict cookie to SSL? cookieSlidingExpiration="true" // Renew expiring cookies? createPersistentCookie="false" // Issue persistent cookie? cookieProtection="All" /> // Cookie protection level --> </system.web> </configuration>