Download presentation
Presentation is loading. Please wait.
1
10 – 12 APRIL 2005 Riyadh, Saudi Arabia
2
Securing ASP.Net applications for the production world
Programming ASP.NET Securing ASP.Net applications for the production world Abdellatif Tarhine Microsoft Regional Director for North Africa Copyright ©
3
Agenda ASP.NET security basics Forms authentication Membership service
Authorization Security principals Forms authentication Membership service Login controls Role Management service
4
ASP.NET Security Authorization Impersonation Authentication
What is the caller allowed to do? ACL Authorization URL Authorization Use process identity or caller identity? Impersonation Authentication Windows Passport Forms Who did the request come from?
5
Windows Authn/File Authz
Anonymous access disabled Authentication mode="Windows" ACL IIS ASP.NET ASPX Ammar A A IIS creates access token identifying Ammar and passes it to ASP.NET ASP.NET checks ACL on requested file and fails request if Ammar lacks read permission
6
Forms Authn/URL Authz T T Ammar ASP. NET Login Page ASPX Ammar ASP.
First access - Redirect to login page URL Ammar ASP. NET Login Page ASPX T Authentication ticket Next access - Authenticated access to ASPX URL Ammar ASP. NET ASPX T
7
Setting the Authentication Type
<configuration> <system.web> <!-- mode="Windows|Passport|Forms|None" --> <authentication mode="Windows" /> </system.web> </configuration>
8
Programming ASP.NET Security Principals Every call has an associated security principal object representing current user Page.User and HttpContext.User properties expose IPrincipal for current user GenericPrincipal WindowsPrincipal FormsIdentity WindowsIdentity PassportIdentity GenericIdentity IPrincipal IIdentity Through security principal objects, ASP.NET abstracts the physical nature of the security principal (Windows security principal, forms security principal, etc.), enabling a single code base to deal with differing security principal types Copyright ©
9
Getting the User Name if (User.Identity.IsAuthenticated) {
Programming ASP.NET Getting the User Name if (User.Identity.IsAuthenticated) { string name = User.Identity.Name; } Copyright ©
10
Membership Service Service for managing users and credentials
Programming ASP.NET 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 The Membership service dramatically reduces the amount of code required to implement forms authentication. In ASP.NET 1.x, you had to supply the code to validate and store credentials. In version 2.0, most of that is done for you. The provider model allows credentials to be stored in SQL Server databases or any other medium for which a membership provider is available. Copyright ©
11
Membership Schema Controls Membership API Membership Providers
Programming ASP.NET Membership Schema Controls Login LoginStatus LoginView Other Login Controls Membership API Membership MembershipUser Membership Providers AccessMembershipProvider SqlMembershipProvider Other Membership Providers Membership Data This is one specific example of the provider model--the one used by the Membership service. The application talks to the Membership service through classes such as Membership and MembershipUser. These classes, in turn, read and write membership data by calling a provider. (Each class has a property named Provider that identifies the associated provider.) Each provider interfaces with a particular type of data store. If none of the providers supplied with the Framework supports the data store you wish to use (for example, an Oracle database), you can write a provider of your own or acquire one from a third party. The Membership service is one of several services that are provider-based. Access SQL Server Other Data Stores Copyright ©
12
Programming ASP.NET 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 The Membership class is the gateway to the membership API. It provides static methods for performing key membership tasks such as creating and deleting users, enumerating users, and validating login credentials. Tasks that used to require tens or hundreds of lines of code can now often be accomplished with just one or two lines by invoking Membership methods. Copyright ©
13
Key Membership Methods
Programming ASP.NET 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 All of these methods are static methods. The names are self-explanatory. Membership methods not shown here include FindUsersBy , FindUsersByName, GetNumberOfUsersOnline, and GetUserNameBy . GetNumberOfUsersOnline is interesting because it returns a count of the number of registered users who are currently logged in to your site. A user is considered to be "online" if he or she has submitted a request to the site in the past N minutes, where N is the userIsOnlineTimeWindow value in the <membership> configuration section: <!-- Excerpt from Machine.config.comments --> <membership defaultProvider="…" userIsOnlineTimeWindow="15"> ... </membership> The default userIsOnlineTimeWindow value is 15 minutes. UpdateUser Updates information for a specified user ValidateUser Validates logins based on user names and passwords Copyright ©
14
Creating New Users try {
Programming ASP.NET Creating New Users try { Membership.CreateUser (“Omar", "imbatman", } catch (MembershipCreateUserException e) { // Find out why CreateUser failed switch (e.StatusCode) { case MembershipCreateStatus.DuplicateUsername: ... case MembershipCreateStatus.Duplicate case MembershipCreateStatus.InvalidPassword: default: This example uses Membership.CreateUser to create a new user named Jeff with the password "imbatman" and the address CreateUser can fail for a number of reasons. If it fails, it throws a MembershipCreateUserException. MembershipCreateUserException.StatusCode reveals WHY the call failed, enabling the application that called it to take appropriate action. Incidentally, an overloaded version of CreateUser exists that doesn't throw exceptions; instead, it accepts a MembershipCreateStatus as an out parameter. Copyright ©
15
Programming ASP.NET Validating Logins if (Membership.ValidateUser (UserName.Text, Password.Text)) FormsAuthentication.RedirectFromLoginPage (UserName.Text, RememberMe.Checked); Validating login credentials used to require no small amount of code. That code often proved susceptible to SQL injection attacks and other ploys used by hackers to break down security barriers. Membership.ValidateUser reduces the task of validating login credentials to one simple line of code and indirectly provides a measure of security against SQL injection attacks ("indirectly" because the actual querying of the membership data store is done by membership providers, but providers such as SqlMembershipProvider contain built-in safeguards against SQL injection attacks). Copyright ©
16
The MembershipUser Class
Programming ASP.NET 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 The second most important class in the Membership API is MembershipUser, which represents individual users registered in membership data stores. MembershipUser exposes information about users through properties such as UserName and CreationDate. Copyright ©
17
Key MembershipUser Properties
Programming ASP.NET Key MembershipUser Properties Name Description Comment Storage for user-defined data CreationDate Date user was added to the membership data store User's address LastLoginDate Date user last logged in successfully LastPasswordChangedDate Date user's password was last changed Information about users is exposed through the properties of the MembershipUser class. For the most part, the property names are self-explanatory. The Comment property, whose type is string, provides storage for user-defined data. If you want to attach additional information to each MembershipUser, you can store that information in Comment. Not shown here (but mentioned in a subsequent slide) is the IsApproved property, which, when set to false, prevents that user from logging in. Is Approved is useful for suspending login privileges. UserId Unique user ID generated by membership provider UserName User's registered user name Copyright ©
18
Key MembershipUser Methods
Programming ASP.NET 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 MembershipUser implements public methods which by and large have to do with password handling. GetPassword retrieves a user's password, but it does so conditionally. Membership providers have a Boolean property named EnablePasswordRetrieval that indicates whether GetPassword will actually retrieve a password. By default, the two membership providers included in beta 1--AccessMembershipProvider and SqlMembershipProvider-- store one-way password hashes rather than passwords, so they don't allow passwords to be retrieved. You can determine ahead of time whether MembershipUser.GetPassword will work by checking Membership.EnablePasswordRetrieval. The value returned is the value of the current provider's EnablePasswordRetrieval property. * Works if Membership.EnablePasswordRetrieval is true Copyright ©
19
Suspending Login Privileges
Programming ASP.NET 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 { 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 (); In beta 2, the Membership service will include support for disabling accounts after a specified number of failed logins within a specified time period. In beta 1, you have to do it on your own. This example uses MembershipUser.Comment to store a count of consecutive failed logins. Setting MembershipUser.IsApproved to false when the count reaches 5 suspends logins for that account until IsApproved is restored to true. Copyright ©
20
Membership Providers Membership is provider-based
Programming ASP.NET Membership Providers Membership is provider-based Provider provides interface between membership service and physical data store Beta 1 ships with two providers AccessMembershipProvider (Access)* SqlMembershipProvider (SQL Server) Use custom providers for other data stores A great way to lead off this slide is to ask the question "So where is membership data stored?" Answer by saying "That depends on the provider. ASP.NET 2.0 ships with membership providers for Microsoft Access and Microsoft SQL Server databases. If neither of those suits your needs, you can write a provider of your own or acquire one from a third party." Note that Access will be replaced by SQL Server Express as a membership data store in beta 2. SQL Server Express will be served by the same membership provider as SQL Server. * Will be replaced by SQL Express provider in beta 2 Copyright ©
21
Using the SQL Server Provider
Programming ASP.NET Using the SQL Server Provider <configuration> <system.web> <membership defaultProvider="AspNetSqlProvider" /> </system.web> </configuration> It's worth noting here that you typically don't make this change to Web.config by hand. Instead, you use the Web Site Administration Tool, which edits Web.config for you. Also, someone has to create the SQL Server database that the Membership service uses to store membership data. You can create that database with the Aspnet_regsql.exe tool that comes with beta 1. In beta 2, the Web Site Administration Tool will probably be able to create the database for you. Copyright ©
22
Provider Configuration
Programming ASP.NET 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 address? Exposed as properties of provider class Initialized from CONFIG files Beta 2 will enhance the membership provider model to include support for automatically disabling accounts following a specified number of failed logins. Copyright ©
23
Changing Provider Settings
Programming ASP.NET 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="/" requiresUnique ="false" passwordFormat="Hashed" description="Stores and retrieves membership data ..." /> </providers> </membership> This example demonstrates how one might configure the Membership service to talk to a remote SQL Server database rather than a local one. The connectionStringName attribute refers to a connection string (not shown) that points to a database on another machine. The default AspNetSqlProvider configuration--the one documented in Machine.config.comments--uses a connection string named "LocalSqlServer" that refers to a database on the same machine. This example deregisters AspNetSqlProvider and reregisters it with a different connectionStringName attribute. An alternative is to register the provider under a different name (eliminating the need for the <remove> element) and add a defaultProvider attribute to the <membership> element selecting the new provider. Copyright ©
24
Login Controls Control Description ChangePassword
Programming ASP.NET 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 Combined with the Membership service, these new controls further reduce the amount of code required to implement forms authentication. They also promote a standard look and feel. Despite their high level of integration with the Membership service, these controls can also be used without it. LoginView Displays different views based on login status and roles PasswordRecovery UI for recovering forgotten passwords Copyright ©
25
Role Management Service
Programming ASP.NET Role Management Service Role-based security in a box Declarative access via Web Site Admin Tool Programmatic access via Roles class Roles class contains static methods for creating roles, adding users to roles, etc. Maps users to roles on each request Replaces Application_AuthenticateRequest Provider-based for flexible data storage In ASP.NET 1.x, combining forms authentication with role-based authorization required the developer to write code--typically an Application_AuthenticateRequest method in Global.asax--to append role information to each request. The Role Management service (or "role manager") does this for you, making role-based security a snap to implement. Like the login controls, this service integrates tightly with the Membership service but can also be used without it. Copyright ©
26
Role Management Schema
Programming ASP.NET Role Management Schema Controls Login LoginStatus LoginView Other Login Controls Roles API Roles Role Providers AccessRoleProvider SqlRoleProvider Other Role Providers Roles Data The Role Management API is embodied in the Roles class, which provides methods for creating roles, adding users to roles, and more. The Roles class doesn't interact with roles data stores directly; rather, it uses role providers. Access SQL Server Other Data Stores Copyright ©
27
The Roles Class Gateway to the Role Management API
Programming ASP.NET 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 The read-only static properties mentioned above include properties named CacheRolesInCookie, CookieName, CookiePath, CookieProtectionValue, CookieRequireSSL, CookieSlidingExpiration, CookieTimeout, and CreatePersistentCookie. As described a few slides hence, the Role Management service caches roles data in cookies by default to avoid having to consult the roles data store on every request. You can read these Roles properties to determine whether roles are being cached in cookies and, if they are, what the caching parameters are. The property values are initialized in the <roleManager> configuration section. They can be read (but not written) at run-time. Copyright ©
28
Key Roles Methods Name Description AddUserToRole Adds a user to a role
Programming ASP.NET 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 Once again, the method names are self-explanatory. All of these methods are static, meaning they're called using the syntax Roles.MethodName and do not require a class instance. IsUserInRole Indicates whether a user belongs to a specified role RemoveUserFromRole Removes a user from the specified role Copyright ©
29
Creating a New Role if (!Roles.RoleExists ("Developers")) {
Programming ASP.NET Creating a New Role if (!Roles.RoleExists ("Developers")) { Roles.CreateRole ("Developers"); } This example first checks to see if a role named "Developers" exists, and then creates it if it doesn't. Copyright ©
30
Adding a User to a Role string name = Membership.GetUser ().Username;
Programming ASP.NET Adding a User to a Role string name = Membership.GetUser ().Username; Roles.AddUserToRole (name, "Developers"); This example adds a user to the "Developers" role created in the previous example. Membership.GetUser returns a MembershipUser reference representing the current user--the one who submitted the request that allowed this code to execute. A given user can belong to multiple roles, something that is very common on real-world sites. Note that AddUserToRole is one of four Roles methods for adding users to roles. The others are AddUserToRoles, AddUsersToRole, and AddUsersToRoles. The complementary Roles.RemoveUser(s)FromRole(s) methods remove users from roles. Copyright ©
31
Enabling the Role Manager
Programming ASP.NET Enabling the Role Manager Role management is disabled by default Enable it via Web.config: <configuration> <system.web> <roleManager enabled="true" /> </system.web> </configuration> The Role Management service is disabled by default and must be explicitly enabled if it's to be used. It's enabled via a simple configuration directive. Like most other administrative changes in ASP.NET 2.0, role management is typically enabled through the Web Site Administration Tool rather than by manually modifying Web.config. The Web Site Administration Tool also provides a UI for creating and deleting roles, adding users to roles, removing users from roles, and performing other role management tasks. Copyright ©
32
Programming ASP.NET Role Caching Role manager offers option for caching role 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? Performance would suffer if the Role Management service accessed a database or other role data store in each and every request. Therefore, the role manager caches role data so it can determine what role or roles a user belongs without consulting the data store. Caching is performed by storing a list of the roles to which a user belongs in a cookie. When a request arrives from a user, the role manager determines what roles that user belongs to by inspecting the cookie. Like authentication cookies, role cookies are encrypted and validated by default to protect the information inside them. Otherwise, one could spoof the role manager by submitting cookies containing bogus role names. Once issued, a role cookie is valid for 30 minutes by default. Through Web.config, you can change the cookie's lifetime. You also have the option of enabling sliding expiration, which renews the cookie each time it's submitted, and of turning role caching off. In ASP.NET 1.x, it was very common to cache roles in cookies, often in the UserData property of forms authentication cookies. However, implementing role caching required non-trivial code. The beauty of role caching in ASP.NET 2.0 is that it's handled entirely by the Role Management service and requires no code on your part. Role management still works if cookies are disabled in the client's browser, but performance will suffer because the role manager must consult the roles data store on each request. Copyright ©
33
Enabling Role Caching <configuration> <system.web>
Programming ASP.NET 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> The options that you can configure for role cookies through the <roleManager> element closely parallel the options you can configure for authentication cookies through the <forms> element. Copyright ©
34
Role Management Providers
Programming ASP.NET Role Management Providers Role management is provider-based Beta 1 ships with four providers AccessRoleProvider (Access)* AuthorizationStoreRoleProvider (AuthMan) SqlRoleProvider (SQL Server) WindowsTokenRoleProvider (Windows) Use custom providers for other data stores Access will be replaced by SQL Server Express as a provider data store in beta 2. SQL Server Express will be served by the same providers as SQL Server. * Will be replaced by SQL Express provider in beta 2 Copyright ©
35
Using the SQL Server Provider
Programming ASP.NET Using the SQL Server Provider <configuration> <system.web> <roleManager enabled="true" defaultProvider="AspNetSqlRoleProvider" /> </system.web> </configuration> A simple configuration change is sufficient to move role data from an Access database to a SQL Server database. SqlRoleProvider stores role data in the same ASP.NET database that the SqlMembershipProvider stores membership data in, albeit in a different table. Before switching to the SQL Server role provider, be sure that the ASP.NET SQL Server database exists. If it doesn't, you can create it with Aspnet_regsql.exe. Copyright ©
36
Programming ASP.NET Copyright © 2001-2002
© 2005 Microsoft Corporation. All rights reserved. This presentation is for informational purposes only. MICROSOFT MAKES NO WARRANTIES, EXPRESS OR IMPLIED, IN THIS SUMMARY. Copyright ©
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.