1. Trang chủ
  2. » Công Nghệ Thông Tin

Professional ASP.NET 1.0 Special Edition- P26 ppt

40 77 0

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

THÔNG TIN TÀI LIỆU

Thông tin cơ bản

Định dạng
Số trang 40
Dung lượng 1,64 MB

Nội dung

to set any specific access permissions for the users we authenticate. In other words, providing that we are happy for all users that are listed in the <authentication> section to have access to all resources in the application using any type of HTTP method ( POST, GET, HEAD), we can use: <authorization> <deny users="?" /> </authorization> Don't be tempted to try and set Windows ACL permissions on resources for the users you specify when using forms-based authentication. Even if Windows accounts do exist for these users, they are not used when the user logs in via forms-based authentication. All access will be performed under the context of the ASP.NET process account (which must have access to the resource). Custom Lists of User Credentials All our forms-based authentication configuration examples so far have used the <credentials> section of web.config to store the list of users that we authenticate requests against. In many cases this is not practical. Rather than manually editing a text file to add and remove users, we will often want to store user details elsewhere - maybe in a database table, an XML document, or even Active Directory. However, it's still useful to be able to take advantage of the other features that forms-based authentication provides, such as automatic redirection to a login page, encryption and validation of the authentication cookie, and integration with the environment (which allows you to retrieve the user's details elsewhere in your code - more details of this coming up later). It's easy to accomplish lookups of user credentials in other data stores, as the examples at the end of the chapter demonstrate. For example, we can use the relational data access capabilities of .NET to retrieve values from a relational database using SQL statements or stored procedures, or we can use classes from the System.Xml namespace to access XML documents. Programmatic Security and Personalization The techniques we've described so far can be used to control access to resources based on the principle of uniquely identifying a user through authentication, and then checking that user's access permission for a resource through authorization. This is sufficient to implement the common types of access control requirement for most applications. However, there are times when we want to be able to control access on a more granular level, or just be able to tell who the current user is within our code. These two techniques are often referred to under the generic terms "programmatic security" and "personalization". We'll look at both of these next, as we see how we can get information about the currently logged-on user. Roles and Identity Overview Once a user has been authenticated, the system knows at least something about that user. At minimum, it knows the username (the identity) and the type of authentication that was carried out. In the case of " Windows" authentication, it also knows which roles (that is, which Windows account groups) the user is a member of. We can access this information in our code, and use it to tailor the way that our applications behave. For example, we can display different pages or change the content of pages depending on the specific user, or on the groups that they are members of. This is a very useful feature, as the only alternative would be to create multiple copies of the page, and set up permission to access each page for the appropriate users. And even then, the only way that the user would know which page they could access would be to try them all. Not exactly a user-friendly approach! There is also the situation where we allow each user to personalize their pages within an application - perhaps to show different content, or just to change the font size, background color, etc. Again, we need to know who the user is so that we can build the appropriate pages. Maybe one user wants to see the current news headlines on their "home" page in our application, while another just wants the daily "Dilbert" cartoon. Getting the User Identity and Role The technique we use to get the user's identity depends on the type of authentication we used originally. ASP.NET exposes the IPrincipal object as the User property of the current HttpContext object (the context within which the page is executing). Through the Identity property, the User object exposes a reference to the IIdentity object that describes the current user. This object provides a range of properties that we can use to identify our current user. The three we use most often are: Name Returns the username or the name of the account that the user logged on with, including the domain name if it was a Windows domain account. IsAuthenticated Returns True if the current user has been authenticated. AuthenticationType Returns a string indicating the authentication method used - for example " Forms", "NTLM", " Basic", "Passport" Depending on the type of authentication used, the Identity property will actually be an instance of one of three different objects. For Windows authentication, the property returns a WindowsIdentity object, for Passport authentication it returns a PassportIdentity object, and for Forms-based authentication it returns a FormsIdentity object. The three properties listed above are common to all these objects: strUserName = User.Identity.Name blnAuthenticated = User.Identity.IsAuthenticated strAuthType = User.Identity.AuthenticationType However, the different Identity objects also expose properties that are specific to the type of authentication used. For example, the WindowsIdentity object exposes properties for the Windows security token, and Boolean values indicating if the account is a Guest account, an anonymous account, or a System account. The FormsIdentity object exposes the current user's cookie "ticket" value, and the PassportIdentity object exposes a host of properties and methods that are specific to this type of authentication. A full list of all the properties and methods for each object is included in the .NET Framework Class Library section of the SDK. The namespace containing the class that implements the Identity object (System.Web.Security) is imported into ASP.NET pages by default, but to create a specific reference to a WindowsIdentity object we also need to import the System.Security.Principal namespace: <%@Import Namespace="System.Security.Principal" %> This allows us to cast the User.Identity to a WindowsIdentity object, and use the extra properties and methods it provides: Checking the User's Role If Windows authentication was used, it's possible to tell which Windows account group the current user is a member of. Or rather, to be more exact, it's possible to tell if the user is a member of a group that we specify. For security reasons, we can't enumerate the list of groups - instead we specify the group name in a call to the IsInRole method. This a method of the User object for the current context: blnResult = User.IsInRole("MyDomainName\SalesDept") This method is useful if we want to change the behavior of a page or application based on the Windows account group that the user is a member of. For example, we can display different menus or links pages for members of the Administrators group, or change the appearance of pages for members of a group named SalesDept compared to the appearance when a member of the AccountingDept group accesses them. To test for a local (machine-level) account group we include the machine name instead of the domain name: blnResult = User.IsInRole("MyMachineName\SalesDept") Using Built-in Account Groups Windows 2000 includes several built-in groups, and it adds users to these groups automatically. For example, all user accounts are automatically members of the built-in Users group, and the administrator account is a member of the built-in Administrators group. To specify one of these built-in groups, we must include the word BUILTIN as though it is the domain name, for example: blnResult = User.IsInRole("BUILTIN\Users") blnResult = User.IsInRole("BUILTIN\Administrators") However, instead of using the name of the group directly, we can substitute values from the enumeration named WindowsBuiltInRole to specify the groups that are built into Windows. This is useful because it will detect the groups or individual accounts if they have been renamed, and will also work on platforms other than Windows 2000 and in other localized operating system languages. For example, using WindowsBuiltInRole.Administrator will include the built-in Administrator account, even if we have renamed it. The full list of members of this enumeration is: WindowsBuiltInRole.AccountOperator WindowsBuiltInRole.Administrator WindowsBuiltInRole.BackupOperator WindowsBuiltInRole.Guest WindowsBuiltInRole.PowerUser WindowsBuiltInRole.PrintOperator WindowsBuiltInRole.Replicator WindowsBuiltInRole.SystemOperator WindowsBuiltInRole.User ASP.NET Security Examples So far in this chapter we've been involved mainly in the theory of authentication and access control in ASP.NET applications. In this section of the chapter, we'll look at some examples that use the different aspects of security we've been exploring. The samples cover:  Configuring a Web application using Windows authentication  Accessing the user's identity within this application  Accessing the user's role within this application  Configuring a Web application using forms-based authentication  Using different types of user credentials lists  Accessing the user's identity within this application  A simple personalization example Obtaining the Example Files The example files for this chapter can be downloaded from the Wrox Press Web site at http://www.wrox.com/Books/Book_Details.asp?isbn=1861004885. Follow the links to the page containing the downloadable code. This includes a subfolder named security, in which you'll find the examples we use here. You can also run many of them online at http://www.daveandal.com/profaspnet/. The default.htm menu page provides links to the example pages: Setting Up the Examples on Your Server Before you can use the examples we provide, there are a couple of things you need to do. First, you must create a virtual root to each of the subfolders containing the example pages within Internet Services Manager. In the Default Web Site entry for your server, create new virtual roots by right clicking and selecting New | Virtual Directory: In the Wizard that appears, enter the appropriate alias from the list below, select the corresponding directory where you installed the example files, and then ensure that you leave the Read and Run Scripts permissions selected. The four aliases we used (and which are included in the links on the default.htm menu page) are:  Alias secure-forms pointing to the folder in the examples named security\forms-based  Alias secure-custom-forms for the folder named security\custom-forms-based  Alias secure-windows for the folder in security\windows  Alias secure-personalization for the folder named security\personalization Creating the Windows Test Account and Groups Our Windows authentication example uses a local user account named TestUser, and two local groups named TestGroup and NoMembers. You should create these using the Computer Management utility on your server - avoid using a domain controller machine as it will create domain-level accounts rather than local accounts. Right-click the Users entry in Local Users and Groups, and select New User. Enter the account name TestUser, a simple password that you can remember, uncheck User must change password at next logon, and check User cannot change password . Then click Create followed by Close: Now select the Groups entry, right-click, and select New Group. Name the new group TestGroup, click Add, and select the TestUser account and then your own domain or local user account as members of the group. Click Create to create this group, and then enter the name NoMembers for another group and click Create again followed by Close. As the name suggests, you shouldn't add any members to the NoMembers group: Creating the UserList Database The only other task is to create the database of users for the "custom-forms-based" and "personalization" examples. We've provided a SQL script file named make-security-db.sql in the security folder of the samples that will do this for you. It adds a user named anon to SQL server for access to this database. Full instructions on creating the database are included in the file database-readme.txt in the same folder as the SQL script. Note that you will also have to recreate the password hash values and update the database for the final example, as the hash is machine-dependent (it depends on the value of the machineKey element in web.config, for which the default value is AutoGenerate - as we saw earlier). You can use the sample page described later in this section to create the new hashes for your machine. Windows Authentication Example The first example, Using Windows-based Authentication and Authorization, demonstrates how we can use Windows authentication and authorization with a Web site or Web application directory. It uses a web.config file with the following structure: <configuration> <system.web> <authentication mode="Windows" /> <identity impersonate="true" /> <authorization> <allow roles="BUILTIN\Administrators" users="DANDARE\Administrator,DANDARE\TestUser" /> <deny users="*" /> </authorization> </system.web> </configuration> Remember to edit the machine name when you run the example on your own server. This instructs the server to authenticate the user through IIS and Windows so they must login using a valid Windows account. We have also specified that we want to use impersonation, so the application will run under the context of this account. Then, in the <authorization> section, we specify that only members of the built-in Administrators group, the local Administrator account on the machine named DANDARE, and the local test user account named TestUser (on the same machine) can access the folder and its contents. If we try and open the page under the context of a different account, we are denied access. In the following screenshot we've accessed the page from a machine that is not on the domain, and specified a username and password combination for an account that does exist on the target server, but which is not included in the list of users we specified within the web.config file: If we now log in using a suitable account that is included in the list in the web.config file, we see a page that shows our account login name (our username), and a selection of other information about our account. In the following two screenshots, we've logged in using the TestUser account we created earlier, and our own domain account that has the username alex. You can see the account name, complete with the machine or domain name, the authentication method used, the type of account, and the groups that the account is a member of: [...]... restricted pages You can also check your browser's Temporary Internet Files folder to confirm that the cookie is no longer there (press F5 to refresh the list) How This Example Works When users first access an ASP.NET page in this folder, they are redirected to the page login.aspx The HTML section of the login.aspx page contains a with textboxes for the username and password, a checkbox where the user... /> This would be a security risk if anyone could get to see the web.config file They cannot download the file from our site, as all requests for this file are blocked automatically by ASP.NET However, local users might access it, and could then see the complete list of username/password combinations that are valid for the site To prevent this, we can encrypt the passwords within the... used earlier) provides an easy way to do this We've included an example page that takes a password and encrypts it using either the SHA1 or MD5 algorithm These are the two encryption methods supported by ASP.NET Password Hashing Example The page is named hash-password.aspx and is in the security folder of the samples we provide for this chapter You can open it from the main menu page (default.htm) in the... minimize the code required to access it We've got a root element , within which is a list of elements that are the usernames The value of each element is that user's password: test test test This file, named userlist.xml, is placed in the same folder as the login page We'll see... outMessage.InnerHtml = "Error accessing database." _ & objError.Message & "" & objError.Source Exit Sub ' and stop execution End Try End If Authenticating the User Now we can actually tell ASP.NET that we have validated the user's credentials and that they should be authenticated and receive the appropriate cookie so that they can access our application If our flag variable is True, we simply... example Simple Personalization Example The final example in this chapter, A Simple Example of Personalization for Each User, demonstrates how we can implement personalization features much more easily in ASP.NET than in previous versions of ASP At the same time, it demonstrates more uses for "programmatic security" When you open the example page, it immediately redirects you to the login page, as in the . can be downloaded from the Wrox Press Web site at http://www.wrox.com/Books/Book_Details .asp? isbn =18 6 10 04885. Follow the links to the page containing the downloadable code. This includes a subfolder. WindowsBuiltInRole.User ASP. NET Security Examples So far in this chapter we've been involved mainly in the theory of authentication and access control in ASP. NET applications. In this. individual accounts if they have been renamed, and will also work on platforms other than Windows 200 0 and in other localized operating system languages. For example, using WindowsBuiltInRole.Administrator

Ngày đăng: 03/07/2014, 07:20