security. agenda asp.net security basics authenticationauthorization security principals forms...
DESCRIPTION
ASP.NET Security AuthenticationAuthentication AuthorizationAuthorization ACL Authorization URL Authorization Windows Passport Forms ImpersonationImpersonation Who did the request come from? What is the caller allowed to do? Use process identity or caller identity?TRANSCRIPT
AgendaAgendaASP.NET security basicsASP.NET security basics
AuthenticationAuthenticationAuthorizationAuthorizationSecurity principalsSecurity principals
Forms authenticationForms authenticationMembership serviceMembership serviceLogin controlsLogin controlsRole Management serviceRole Management service
ASP.NET SecurityASP.NET Security
AuthenticationAuthentication
AuthorizationAuthorizationACL AuthorizationURL Authorization
WindowsPassportForms
ImpersonationImpersonation
Who did the request come from?
What is the caller allowed to do?
Use process identity or caller identity?
Windows Authn/File AuthzWindows Authn/File Authz
ACL
Bob IIS ASP.NET A ASPXA
IIS creates access token identifying Bob and passes it to ASP.NET
ASP.NET checks ACL on requested file and fails request if Bob lacks read permission
Anonymousaccess disabled
Authenticationmode="Windows"
URL
Forms Authn/URL AuthzForms Authn/URL Authz
ASP.NETBob ASPXLogin
Page T
URL
ASP.NETBob ASPXT
First access - Redirect to login page
Next access - Authenticated access to ASPX
Authentication ticket
Setting the Authentication Setting the Authentication TypeType<configuration> <system.web> <!-- mode="Windows|Passport|Forms|None" --> <authentication mode="Windows" /> </system.web></configuration>
Security PrincipalsSecurity PrincipalsEvery call has an associated security Every call has an associated security principal object representing current principal object representing current useruser
Page.User and HttpContext.User Page.User and HttpContext.User properties expose IPrincipal for properties expose IPrincipal for current usercurrent user
GenericPrincipalWindowsPrincipal
IPrincipalFormsIdentityWindowsIdentityPassportIdentityGenericIdentity
IIdentity
Getting the User NameGetting the User NameIf User.Identity.IsAuthenticated Then Dim name As String = User.Identity.NameEnd If
Membership ServiceMembership ServiceService for managing users and Service for managing users and credentialscredentials
Declarative access via Web Site Admin Declarative access via Web Site Admin ToolToolProgrammatic access via Membership Programmatic access via Membership and MembershipUser classesand MembershipUser classes
Membership class provides base Membership class provides base servicesservicesMembershipUser class represents MembershipUser class represents users and provides additional servicesusers and provides additional servicesProvider-based for flexible data Provider-based for flexible data storagestorage
Membership SchemaMembership Schema
Membership API
MembershipData
Access OtherData Stores
Controls Login LoginStatus LoginView
AccessMembershipProvider Other MembershipProviders
Membership Providers
Membership MembershipUser
SqlMembershipProvider
SQL Server
Other LoginControls
The Membership ClassThe Membership ClassProvides static methods for Provides static methods for performing key membership tasksperforming key membership tasks
Creating and deleting usersCreating and deleting usersRetrieving information about usersRetrieving information about usersGenerating random passwordsGenerating random passwordsValidating loginsValidating logins
Also includes read-only static Also includes read-only static properties for acquiring data about properties for acquiring data about provider settingsprovider settings
Key Membership MethodsKey Membership MethodsName 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 objectsrepresenting 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 UsersCreating New UsersTry Membership.CreateUser ("Jeff", "imbatman", "[email protected]")Catch e As MembershipCreateUserException ' Find out why CreateUser failed Select Case e.StatusCode Case MembershipCreateStatus.DuplicateUsername ... Case MembershipCreateStatus.DuplicateEmail ... Case MembershipCreateStatus.InvalidPassword ... Case Else ... End SelectEnd Try
Validating LoginsValidating LoginsIf Membership.ValidateUser (UserName.Text, Password.Text) Then FormsAuthentication.RedirectFromLoginPage (UserName.Text, _ RememberMe.Checked)End If
The MembershipUser The MembershipUser ClassClass
Represents individual users registered Represents individual users registered in the membership data storein the membership data storeIncludes numerous properties for Includes numerous properties for getting and setting user infogetting and setting user infoIncludes methods for retrieving, Includes methods for retrieving, changing, and resetting passwordschanging, and resetting passwordsReturned by Membership methods Returned by Membership methods such as GetUser and CreateUsersuch as GetUser and CreateUser
Key MembershipUser Key MembershipUser PropertiesProperties
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
LastPasswordChangedDateDate user's password was last changed
UserId Unique user ID generated by membership provider
UserName User's registered user name
Key MembershipUser Key MembershipUser MethodsMethods
Name Description
ChangePassword Changes user's password
ChangePassword-QuestionAndAnswer
Changes question and answer used for passwordrecovery
GetPassword* Retrieves a password
ResetPassword Resets a password by setting it to a new random password
* Works if Membership.EnablePasswordRetrieval is true
Suspending Login Suspending Login PrivilegesPrivilegesIf Membership.ValidateUser (UserName.Text, Password.Text) Then Dim user As MembershipUser = Membership.GetUser(UserName.Text) user.Comment = "0" RedirectFromLoginPage (UserName.Text, RememberMe.Checked)Else Dim user As MembershipUser = Membership.GetUser (UserName.Text) If Not (user Is Nothing) Then ' Get a count of consecutive failed login attempts Dim count As String = Convert.ToInt32 (user.Comment) + 1 ' If the count equals or exceeds 5, suspend login privileges If count >= 5 Then user.IsApproved = False End If
' Update the count of consecutive failed login attempts user.Comment = count.ToString () End IfEnd If
Membership ProvidersMembership ProvidersMembership is provider-basedMembership is provider-based
Provider provides interface between Provider provides interface between membership service and physical data membership service and physical data storestore
Beta 1 ships with two providersBeta 1 ships with two providersAccessMembershipProvider (Access)*AccessMembershipProvider (Access)*SqlMembershipProvider (SQL Server)SqlMembershipProvider (SQL Server)
Use custom providers for other data Use custom providers for other data storesstores
* Will be replaced by SQL Express provider in beta 2
Using the SQL Server Using the SQL Server ProviderProvider<configuration> <system.web> <membership defaultProvider="AspNetSqlProvider" /> </system.web></configuration>
Provider ConfigurationProvider ConfigurationMembership providers support a Membership providers support a number of configuration settingsnumber of configuration settings
How should passwords be stored How should passwords be stored (cleartext, hashed, encrypted)?(cleartext, hashed, encrypted)?Should password recovery be enabled?Should password recovery be enabled?Must each user have a unique e-mail Must each user have a unique e-mail address?address?
Exposed as properties of provider Exposed as properties of provider classclassInitialized from CONFIG filesInitialized from CONFIG files
Changing Provider Changing Provider SettingsSettings<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 ControlsLogin ControlsControl Description
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
PasswordRecoveryUI for recovering forgotten passwords
CreateUserWizard UI for creating new user accounts
ChangePassword UI for changing passwords
Role Management ServiceRole Management ServiceRole-based security in a boxRole-based security in a box
Declarative access via Web Site Admin Declarative access via Web Site Admin ToolToolProgrammatic access via Roles classProgrammatic access via Roles class
Roles class contains static methods Roles class contains static methods for creating roles, adding users to for creating roles, adding users to roles, etc.roles, etc.Maps users to roles on each requestMaps users to roles on each request
Replaces Replaces Application_AuthenticateRequestApplication_AuthenticateRequest
Provider-based for flexible data Provider-based for flexible data storagestorage
Role Management SchemaRole Management Schema
Roles API
Roles Data
Access OtherData Stores
Controls Login LoginStatus LoginView
AccessRoleProvider Other Role Providers
Role Providers
Roles
SqlRoleProvider
SQL Server
Other LoginControls
The Roles ClassThe Roles ClassGateway to the Role Management APIGateway to the Role Management APIProvides static methods for Provides static methods for performing key role management performing key role management taskstasks
Creating and deleting rolesCreating and deleting rolesAdding users to rolesAdding users to rolesRemoving users from roles and moreRemoving users from roles and more
Also includes read-only static Also includes read-only static properties for acquiring data about properties for acquiring data about provider settingsprovider settings
Key Roles MethodsKey Roles MethodsName 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
RemoveUserFromRoleRemoves a user from the specified role
Creating a New RoleCreating a New RoleIf Not Roles.RoleExists ("Developers") Then Roles.CreateRole ("Developers")End If
Adding a User to a RoleAdding a User to a RoleDim name As String = Membership.GetUser ().UsernameRoles.AddUserToRole (name, "Developers")
Enabling the Role Enabling the Role ManagerManager
Role management is disabled by Role management is disabled by defaultdefaultEnable it via Web.config:Enable it via Web.config:
<configuration> <system.web> <roleManager enabled="true" /> </system.web></configuration>
Role CachingRole CachingRole manager offers option for Role manager offers option for caching role data in cookiescaching role data in cookies
Fewer accesses to data storeFewer accesses to data storeBetter performanceBetter performance
Controlled via <roleManager> Controlled via <roleManager> attributes and programmatically attributes and programmatically exposed thru Roles classexposed thru Roles class
Should roles be cached in cookies?Should roles be cached in cookies?Should role cookies be encrypted?Should role cookies be encrypted?How long are role cookies valid?How long are role cookies valid?
Enabling Role CachingEnabling 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 Role Management ProvidersProviders
Role management is provider-basedRole management is provider-basedBeta 1 ships with four providersBeta 1 ships with four providers
AccessRoleProvider (Access)*AccessRoleProvider (Access)*AuthorizationStoreRoleProvider AuthorizationStoreRoleProvider (AuthMan)(AuthMan)SqlRoleProvider (SQL Server)SqlRoleProvider (SQL Server)WindowsTokenRoleProvider (Windows)WindowsTokenRoleProvider (Windows)
Use custom providers for other data Use custom providers for other data storesstores* Will be replaced by SQL Express provider in beta 2
Using the SQL Server Using the SQL Server ProviderProvider<configuration> <system.web> <roleManager enabled="true" defaultProvider="AspNetSqlRoleProvider" /> </system.web></configuration>