Building Secure Applications using Membership and Role

Download Report

Transcript Building Secure Applications using Membership and Role

Building Secure Applications using
Membership and Role Management with
Visual Studio 2005 and ASP.NET 2.0
- David Silverlight
[email protected]
http://www.NonProfitWays.com
Overview

Membership service




Membership API
Membership providers
Login controls
Role Management service



Roles class
Role caching
Role providers
Membership Service

Service for managing users and credentials





Declarative access via Web Site Admin Tool
Programmatic access via Membership and MembershipUser classes
Membership class provides base services
MembershipUser class represents users and provides additional
services
Provider-based for flexible data storage
Membership Schema
Controls
Login
LoginStatus
LoginView
Membership API
Membership
MembershipUser
Membership Providers
SqlMembershipProvider
Membership
Data
SQL Server
Other Membership
Providers
Other
Data Stores
Other Login
Controls
The Membership Class

Provides static methods for performing key membership tasks





Creating and deleting users
Retrieving information about users
Generating random passwords
Validating logins
Also includes read-only static properties for acquiring data about
provider settings
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", "[email protected]");
}
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
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
ChangePasswordQuestionAndAnswer
Changes question and answer used for password
recovery
GetPassword*
Retrieves a password
ResetPassword
Resets a password by setting it to a new random password
* Works if Membership.EnablePasswordRetrieval is true
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 ();
}
}
Membership Providers

Membership is provider-based


ASP.NET ships with one provider


Provider provides interface between membership service and physical
data store
SqlMembershipProvider (SQL Server or SQL Server Express)
Use custom providers for other data stores
Provider Configuration

Membership providers support a number of configuration settings





How should passwords be stored (cleartext, hashed, encrypted)?
Should password recovery be enabled?
Must each user have a unique e-mail address?
Exposed as properties of provider class
Initialized from CONFIG files
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>
Membership
Name
Title
Microsoft Corporation
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
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"
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>
Login Controls
Role Management Service

Role-based security in a box




Roles class contains static methods for creating roles, adding users
to roles, etc.
Maps users to roles on each request


Declarative access via Web Site Admin Tool
Programmatic access via Roles class
Replaces Application_AuthenticateRequest
Provider-based for flexible data storage
Role Management Schema
Controls
Login
Roles API
LoginStatus
LoginView
Other Login
Controls
Roles
Role Providers
SqlRoleProvider
Other Role Providers
Roles Data
SQL Server
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
Also includes read-only static properties for acquiring data about
provider settings
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


Role management is disabled by default
Enable it via Web.config:
<configuration>
<system.web>
<roleManager enabled="true" />
</system.web>
</configuration>
Role Caching

Role manager caches roles data in cookies



Fewer accesses to data store
Better performance
Controlled via <roleManager> attributes and programmatically
exposed thru Roles class



Should roles be cached in cookies?
Should role cookies be encrypted?
How long are role cookies valid?
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>
Role Management Providers


Role management is provider-based
ASP.NET 2.0 ships with two providers



SqlRoleProvider (SQL Server)
WindowsTokenRoleProvider (Windows)
Use custom providers for other data stores
Role Management
Name
Title
Microsoft Corporation
What We Covered…




The Simplicity of the Membership and Membership User Class
Sweet New Set of Login Controls
Role Management in a box
Administration made easy with the Web Site Admin Tool
Any Questions?
David Silverlight
[email protected]
http://www.nonprofitways.com
http://www.XMLPitstop.com
Thank you!!!