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

Professional ASP.NET 3.5 in C# and Visual Basic Part 147 potx

10 490 0

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

THÔNG TIN TÀI LIỆU

Thông tin cơ bản

Định dạng
Số trang 10
Dung lượng 239,5 KB

Nội dung

Evjen c31.tex V2 - 01/28/2008 4:01pm Page 1425 Chapter 31: Configuration The browser definition file format defines each browser as an entity, self-contained in a < browser > XML element. Each browser has its own ID that describes a class of browser and its parent class. The root node of a browser definition file is the < browsers > element and multiple browser entries identified using the id attribute of the < browser > element. Listing 31-15 shows a section of the ie.browser file. Listing 31-15: Content of IE.browser file < browsers > < browser id="IE" parentID="Mozilla" > < identification > < userAgent match="^Mozilla[^(]* \ ([C|c]ompatible; \ s*MSIE (?’version’(?’major’ \ d+)(?’minor’ \ . \ d+)(?’letters’ \ w*))(?’extra’[^)]*)" / > < userAgent nonMatch="Opera" / > < userAgent nonMatch="Go \ .Web" / > < userAgent nonMatch="Windows CE" / > < userAgent nonMatch="EudoraWeb" / > < /identification > < capture > < /capture > < capabilities > < capability name="browser" value="IE" / > < capability name="extra" value="${extra}" / > < capability name="isColor" value="true" / > < capability name="letters" value="${letters}" / > < capability name="majorversion" value="${major}" / > < capability name="minorversion" value="${minor}" / > < capability name="screenBitDepth" value="8" / > < capability name="type" value="IE${major}" / > < capability name="version" value="${version}" / > < /capabilities > < /browser > The id attribute of the < browser > element uniquely identifies the class of browser. The parentID attribute of the < browser > element specifies the unique ID of the parent browser class. Both the id and the parentID are required values. Before running an ASP.NET application, the framework compiles all the browser definitions into an assembly and installs the compilation in GAC. When the browser definition files at the system level are modified, they do not automatically reflect the change in each and every ASP.NET appli cation. Therefore, it becomes the responsibility of the developer or the installation tool to update this informa- tion. You can send the updated browser information to all the ASP.NET applications by running the aspnet_regbrowsers.exe utility provided by the framework. When the aspnet_regbrowsers.exe utility is called, the browser information is recompiled and the new assembly is stored in the GAC; this assembly is reused by all the ASP.NET applications. Nevertheless, browser definitions at the application level are automatically parsed and compiled on demand when the application is started. If any changes are made to the application’s /Browsers directory, the application is automatically recycled. 1425 Evjen c31.tex V2 - 01/28/2008 4:01pm Page 1426 Chapter 31: Configuration Custom Errors When the ASP.NET application fails, the ASP.NET page can show the default error page with the source code and line number of the error. However, this approach has a few problems: ❑ The source code and error message may not make any sense to a less experienced end user. ❑ If the same source code and the error messages are displayed to a hacker, subsequent damage could result. Displaying too much error information could provide important implementation details that you are in most cases going to want to keep from the public. Figure 31-4 shows an example of this. Figure 31-4 However, ASP.NET provides excellent infrastructure to prevent this kind of error information. The < customErrors > section provides a means for defining custom error messages in an ASP.NET appli- cation. The syntax is as follows: < customErrors defaultRedirect="[url]" mode="[on/off/remote]" > < error statusCode="[statuscode]" redirect="[url]" / > < /customErrors > 1426 Evjen c31.tex V2 - 01/28/2008 4:01pm Page 1427 Chapter 31: Configuration ❑ defaultRedirect : Specifies the default URL to which the client browser should be redirected if an error occurs. This is an optional setting. ❑ mode : Specifies if the status of the custom errors is enabled, disabled, or shown only to remote machines. The possible values are On , Off , RemoteOnly . On indicates that the custom errors are enabled. Off indicates that the custom errors are disabled. RemoteOnly indicates that the custom errors are shown only to remote clients. ❑ customErrors :The< customErrors > section supports multiple < error > subelements that are used to define custom errors. Each < error > subelement can include a statusCode attribute and aURL. Authentication In Chapter 21, you see the authentication process in detail. In this section, you can review configuration- specific information. Authentication is a process that verifies the identity of the user and establishes the identity between the server and a request. Because HTTP is a stateless protocol, the authentication information is persisted somewhere in the client or the server; ASP.NET supports both of these. You can store the server-side information in Session objects. When it comes to client side, you have many options: ❑ Cookies ❑ ViewState ❑ URL ❑ Hidden fields ASP.NET 3.5 supports following authentication methods out of the box: ❑ Windows authentication ❑ Passport authentication ❑ Forms Authentication If you would like to disable authentication, you can use the setting mode = "None" : < authentication mode="None" / > Windows Authentication ASP.NET relies on IIS’s infrastructure to implement Windows authentication, and Windows authentica- tion enables you to authenticate requests using Windows Challenge/Response semantics. When the Web server receives a request, it initially denies access to the request (which is a challenge). This triggers the browser to pop up a window to collect the credentials; the request responds with a hashed value of the Windows credentials, which the server can then choose to authenticate. To implement Windows authentication, you configure the appropriate Web site or virtual directory using IIS. You can then use the < authentication > element to mark the Web application or virtual directory with Windows authentication. This is illustrated in Listing 31-16. 1427 Evjen c31.tex V2 - 01/28/2008 4:01pm Page 1428 Chapter 31: Configuration Listing 31-16: Setting authentication to Windows authentication < configuration > < system.web > < authentication mode="Windows" > < /system.web > < /configuration > The < authentication > element can be declared only at the machine, site, or application level. Any attempt to declare it in a configuration file at the subdirectory or page level results in a parser error message. Passport Authentication ASP.NET 3.5 relies on the Passport SDK to implement Passport authentication, which is promoted by Microsoft Corporation. Passport is a subscription-based authentication mechanism that allows end users to remember a single username/password pair across multiple Web applications that implement Pass- port authentication. ASP.NET 3.5 authenticates users based on the credentials presented by users. The Passport service sends a token back to authenticate. The token is stored in a site-specific cookie after it has been authenticated with login.passport.com .Usingthe redirectUrl attribute of the < passport > authentication option, you can control how non-authenticated Passport users are directed, as in the following example: < passport redirectUrl="/Passport/SignIn.aspx" / > Forms Authentication Forms Authentication is the widely used authentication mechanism. Forms Authentication can be con- figured using the < authentication > section along with the < forms > subsection. The structure of an < authentication > section that deals with forms authentication in the configuration file is presented in Listing 31-17. Listing 31-17: The <authentication> section working with forms authentication < configuration > < system.web > < authentication mode="Forms" > < forms name="[name]" loginUrl="[url]" protection="[All|None|Encryption|Validation]" timeout="30" path="/" requireSSL="[true|false]" slidingExpiration="[true|false]" cookieless="UseCookies|UseUri|AutoDetect|UseDeviceProfile" 1428 Evjen c31.tex V2 - 01/28/2008 4:01pm Page 1429 Chapter 31: Configuration defaultUrl="[url]" domain="string" > < credentials passwordFormat="[Clear, SHA1, MD5]" > < user name="[UserName]" password="[password]"/ > < /credentials > < /forms > < /authentication > < /system.web > < /configuration > Each attribute is shown in detail in the following list: ❑ name : Specifies the name of the HTTP authentication ticket. The default value is .ASPXAUTH . ❑ loginUrl : Specifies the URL to which the request is redirected if the current request doesn’t have a valid authentication ticket. ❑ protection : Specifies the method used to protect cookie data. Valid values are All , None , Encryption ,and Validation . ❑ Encryption : Specifies that content of the cookie is encrypted using TripleDES or DES cryp- tography algorithms in the configuration file. However, the data validation is not done on the cookie. ❑ Validation : Specifies that content of the cookie is not encrypted, but validates that the cookie data has not been altered in transit. ❑ All : Specifies that content of the cookie is protected using both data validation and encryp- tion. The configured data validation algorithm is used based on the < machineKey > ele- ment, and Triple DES is used for encryption. The default value is All , and it indicates the highest protection available. ❑ None : Specifies no protection mechanism is applied on the cookie. Web applications that do not store any sensitive information and potentially use cookies for personalization can look at this option. When None is specified, both encryption and validation are disabled. ❑ timeout : Specifies cookie expiration time in terms of minutes. The timeout attribute is a sliding value, which expires n minutes from the time the last request was received. The default value is 30 minutes. ❑ path : Specifies the path to use for the issued cookie. The default value is / to avoid difficul- ties with mismatched case in paths because browsers are strictly case-sensitive when returning cookies. ❑ requireSSL : Specifies whether Forms Authentication should happen in a secure HTTPS connection. ❑ slidingExpiration : Specifies whether valid cookies should be updated periodically when used. When false, a ticket is good for only the duration of the period for which it is issued, and a user must re-authenticate even during an active session. ❑ cookieless : Specifies whether cookieless authentication is supported. Supported values are UseCookies , UseUri , Auto ,and UseDeviceProfile . The default value is UseDeviceProfile . ❑ defaultUrl : Specifies the default URL used by the login control to control redirection after authentication. 1429 Evjen c31.tex V2 - 01/28/2008 4:01pm Page 1430 Chapter 31: Configuration ❑ domain : Specifies the domain name string to be attached in the authentication cookie. This attri- bute is particularly useful when the same authentication cookie is shared among multiple sites across the domain. It is strongly recommended that the loginUrl should be an SSL URL ( https:// ) to keep secure credentials secure from prying eyes. Anonymous Identity Many application types require the capability to work with anonymous users, although this is espe- cially true for e-commerce Web applications. In these cases, your site must support both anonymous and authenticated users. When anonymous users are browsing the site and adding items to a shopping cart, the Web application needs a way to uniquely identify these users. For example, if you look at busy e-commerce Web sites such as Amazon.com or BN.com , they do not have a concept called anonymous users. Rather these sites assign a unique identity to each user. In ASP.NET 1.0 and 1.1, no out-of-the box feature existed to enable a developer to achieve this identifica- tion of users. Most developers used SessionID to identify users uniquely. They experienced a few pitfalls inherent in this method. Since the introduction of ASP.NET 2.0, ASP.NET has had anonymous identity support using the < anonymousIdentification > section in the configuration file. The following listing here in Listing 31-18 shows the < anonymousIdentification > configuration section settings. Listing 31-18: Working with anonymous identification in the configuration file < configuration > < system.web > < anonymousIdentification enabled="false" cookieName=".ASPXANONYMOUS cookieTimeout="100000" cookiePath="/" cookieRequireSSL="false" cookieSlidingExpiration = "true" cookieProtection = "Validation" cookieLess="UseCookies|UseUri|AutoDetect|UseDeviceProfile" domain=" ." / > < /system.web > < /configuration > The enabled attribute within the < anonymousIdentification > section specifies whether the anony- mous access capabilities of ASP.NET are enabled. The other attributes are comparable to those in the authentication section from Listing 31-17. When working with anonymous identification, it is possible that the end user will have cookies disabled in their environments. When cookies are not enabled by the end user, the identity of the user is then stored in the URL string within the end user’s browser. Authorization The authorization process verifies whether a user has the privilege to access the resource he is trying to request. ASP.NET 3.5 supports both file and URL authorization. The authorization process dictated by an application can be controlled by using the < authorization > section within the configuration file. 1430 Evjen c31.tex V2 - 01/28/2008 4:01pm Page 1431 Chapter 31: Configuration The < authorization > section, as presented in Listing 31-19, can contain subsections that either allow or deny permission to a user, a group of users contained within a specific role in the system, or a request that is coming to the server in a particular fashion (such as an HTTP GET request). Optionally, you can also use the < location > section to grant special authorization permission to only a particular folder or file within the application. Listing 31-19: Authorization capabilities from the configuration file < authorization > < allow users="" roles="" verbs="" / > < deny users="" roles="" verbs="" / > < /authorization > URL Authorization The URL Authorization is a service provided by URLAuthorizationModule (inherited from HttpModule ) to control the access to resources such as .aspx files. The URL Authorization is very useful if you want to allow or deny certain parts of your ASP.NET application to certain people or roles. For example, you may want to restrict the administration part of your ASP.NET application only to administrators and deny access to others. You can achieve this very easily with URL Authorization. URL Authorization can be configurable based on the user, the role, or HTTP verbs such as HTTP GET request or HTTP POST request. You can configure URL Authorization in the web.config file with < allow > and < deny > attributes. For example, the following code (Listing 31-20) shows how you can allow the user Bubbles and deny the groups Sales and Marketing access to the application. Listing 31-20: An example of allowing and denying entities from the <authorization> section < system.web > < authorization > < allow users="Bubbles" / > < deny roles="Sales, Marketing" / > < /authorization > < /system.web > The < allow > and < deny > elements support users , roles ,and verbs values.Asyoucanseefromthe previous code example, you can add multiple users and groups by separating them with commas. Two special characters, an asterisk ( * )andaquestionmark( ? ), are supported by URLAuthorization- Module . The asterisk symbol represents all users (anonymous and registered) and the question mark represents only anonymous users. The following code example in Listing 31-21 denies access to all anonymous users and grants access to anyone contained within the Admin role. Listing 31-21: Denying anonymous users < system.web > < authorization > < allow roles="Admin" / > < deny users="?" / > < /authorization > < /system.web > 1431 Evjen c31.tex V2 - 01/28/2008 4:01pm Page 1432 Chapter 31: Configuration You can also grant or deny users or groups access to certain HTTP methods. In the example in Listing 31-22, access to the HTTP GET method is denied to the users contained within the Admin role, whereas access to the HTTP POST method is denied to all users. Listing 31-22: Denying users and roles by verb < system.web > < authorization > < deny verbs="GET" roles="Admin" / > < deny verbs="POST" users="*" / > < /authorization > < /system.web > File Authorization It is possible to construct the authorization section within the configuration file so that what is specified can be applied to a specific file or directory using the < location > element. For example, suppose you have a root directory called Home within your application and nested within that root directory you have a subdirectory called Documents . Suppose you want to allow access to the Documents subdirectory only to those users contained within the Admin role. This scenario is illustrated in Listing 31-23. Listing 31-23: Granting access to the Documents subdirectory for the Admin role < configuration > < location path="Documents" > < system.web > < authorization > < allow roles="Admin" / > < deny users="*" / > < /authorization > < /system.web > < /location > < /configuration > The ASP.NET application does not verify the path specified in the path attribute. If the given path is invalid, ASP.NET does not apply the security setting. You can also set the security for a single file as presented in Listing 31-24. Listing 31-24: Granting access to a specific file for the Admin role < configuration > < location path="Documents/Default.aspx" > < system.web > < authorization > < allow roles="Admin" / > < deny users="*" / > < /authorization > < /system.web > < /location > < /configuration > 1432 Evjen c31.tex V2 - 01/28/2008 4:01pm Page 1433 Chapter 31: Configuration Locking-Down Configuration Settings ASP.NET’s configuration system is quite flexible in terms of applying configuration information to a specific application or folder. Even though the configuration system is flexible, in some cases you may want to limit the configuration options that a particular application on the server can control. For example, you could decide to change the way in which the ASP.NET session information is stored. This lock-down process can be achieved using the < location > attributes allowOverride and allowDefini- tion ,aswellasthe path attribute. Listing 31-25 illustrates this approach. A < location > section in this machine.config file identifies the path "Default Web Site/ExampleApplication" and allows any application to override the < trace > setting through the use of the allowOverride attribute. Listing 31-25: Allowing a <trace> section to be overridden in a lower configuration file < configuration > < location path="Default Web Site/ExampleApplication" allowOverride="true" > < trace enabled="false"/ > < /location > < /configuration > The trace attribute can be overridden because the allowOverride attribute is set to true .Youareableto override the tracing setting in the ExampleApplication ’s web.config file and enable the local < trace > element, thereby overriding the settings presented in Listing 31-25. However, if you had written the attribute as allowOverride = "false" in the < location > section of the machine.config file, the web.config file for ExampleApplication is unable to override that specific setting. ASP.NET Page Configuration When an ASP.NET application has been deployed, the < pages > section of the configuration file enables you to control some of the default behaviors for each and every ASP.NET page. These behaviors include options such as whether you should buffer the output before sending it or whether session state should be enabled for the entire application. An example of using the < pages > section is presented in Listing 31-26. Listing 31-26: Configuring the <pages> section < configuration > < system.web > < pages buffer="true" enableSessionState="true" enableViewState="true" enableViewStateMac="false" autoEventWireup="true" smartNavigation="false" masterPageFile="~/ExampleApplicationMasterPage.master" Continued 1433 Evjen c31.tex V2 - 01/28/2008 4:01pm Page 1434 Chapter 31: Configuration pageBaseType="System.Web.UI.Page" userControlBaseType="System.Web.UI.UserControl" compilationMode="Auto" validateRequest="true" > < namespaces > < add namespace="Wrox.ExampleApplication"/ > < /namespaces > < controls / > < tagMapping / > < /pages > < /system.web > < /configuration > The following list gives you the ASP.NET page configuration information elements in detail: ❑ buffer : Specifies whether the requests must be buffered on the server before it is sent it to the client. ❑ enableSessionState : Specifies whether the session state for the current ASP.NET application should be enabled. The possible values are true , false ,or readonly .The readonly value means that the application can read the session values but cannot modify them. ❑ enableViewState : Specifies whether the ViewState is enabled for all the controls. If the applica- tion does not use ViewState, you can set the value to false in the application’s web.config file. ❑ autoEventWireup : Specifies whether ASP.NET can automatically wire-up common page events such as Load or Error. ❑ smartNavigation : Smart navigation is a feature that takes advantage of IE as a client’s browser to prevent the redrawing that occurs when a page is posted back to itself. Using smart naviga- tion, the request is sent through an IFRAME on the client, and IE redraws only the sections of the page that have changed. By default, this option is set to false . When it is enabled, it is avail- able only to Internet Explorer browsers — all other browsers get the standard behavior. ❑ masterPageFile : Identifies the master page for the current ASP.NET application. If you wish to apply the master page template to only a specific subset of pages (such as pages contained within a specific folder of your application), you can use the < location > element within the web.config file: < configuration > < location path="ExampleApplicationAdmin" > < system.web > < pages masterPageFile="~/ExampleApplicationAdminMasterPage.master" / > < /system.web > < /location > < /configuration > ❑ pageBaseType : Specifies the base class for all the ASP.NET pages in the current ASP.NET appli- cation. By default, this option is set to System.Web.UI.Page . However, if you want all ASP.NET pages to inherit from some other base class, you can change the default via this setting. ❑ userControlBaseType : Specifies the base class for all the ASP.NET user controls in the current ASP.NET application. The default is System.Web.UI.UserControl . You can override the default option using this element. 1434 . those users contained within the Admin role. This scenario is illustrated in Listing 31 - 23. Listing 31 - 23: Granting access to the Documents subdirectory for the Admin role < configuration > < location. specified in the path attribute. If the given path is invalid, ASP. NET does not apply the security setting. You can also set the security for a single file as presented in Listing 31 -24. Listing 31 -24:. file. The following listing here in Listing 31 -18 shows the < anonymousIdentification > configuration section settings. Listing 31 -18: Working with anonymous identification in the configuration

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

TỪ KHÓA LIÊN QUAN