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
Tài liệu đã được kiểm tra trùng lặp

Đ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

Các công cụ chuyển đổi và chỉnh sửa cho tài liệu này

Nội dung

Because HTTP is a stateless protocol, the authentication information is persisted somewhere in the client or the server; ASP.NET supports both of these.. When it comes to client side, yo

Trang 1

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

idattribute of the<browser>element

Listing 31-15 shows a section of theie.browserfile

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>

Theidattribute of the<browser>element uniquely identifies the class of browser TheparentID

attribute of the<browser>element specifies the unique ID of the parent browser class Both theid

and theparentIDare 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 application.

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.exeutility provided by the framework When theaspnet_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/Browsersdirectory, the application is automatically recycled.

Trang 2

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>

Trang 3

❑ 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 areOn,Off,RemoteOnly.Onindicates that the custom errors are

enabled.Offindicates that the custom errors are disabled.RemoteOnlyindicates 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 astatusCodeattribute and

a URL

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 inSessionobjects When it comes to client side, you have

many options:

❑ Cookies

❑ ViewState

❑ 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 settingmode = "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

Trang 4

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

withlogin.passport.com Using theredirectUrlattribute 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"

Trang 5

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 areAll,None,

Encryption, and Validation

❑ Encryption: Specifies that content of the cookie is encrypted usingTripleDESorDES 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 isAll, 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 WhenNoneis specified, both encryption and validation are disabled

❑ timeout: Specifies cookie expiration time in terms of minutes Thetimeoutattribute is a sliding value, which expiresnminutes 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, andUseDeviceProfile The default value isUseDeviceProfile

❑ defaultUrl: Specifies the default URL used by the login control to control redirection after

authentication

Trang 6

❑ 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 theloginUrlshould 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 asAmazon.comorBN.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 usedSessionIDto 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>

Theenabledattribute 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 section within the configuration file

Trang 7

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 byURLAuthorizationModule(inherited fromHttpModule)

to control the access to resources such as.aspxfiles 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 theweb.configfile with<allow>and<deny>attributes For example, the following code (Listing 31-20) shows how you can allow the userBubblesand deny the

groupsSalesandMarketingaccess 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 supportusers,roles, andverbsvalues As you can see from the

previous code example, you can add multiple users and groups by separating them with commas

Two special characters, an asterisk (*) and a question mark (?), 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>

Trang 8

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 calledHomewithin your application and nested within that root directory you have

a subdirectory calledDocuments Suppose you want to allow access to theDocumentssubdirectory only

to those users contained within theAdminrole 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>

Trang 9

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>attributesallowOverrideand allowDefini-tion, as well as thepathattribute

Listing 31-25 illustrates this approach A<location>section in thismachine.configfile identifies the

path"Default Web Site/ExampleApplication"and allows any application to override the<trace>

setting through the use of theallowOverrideattribute

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 theallowOverrideattribute is set totrue You are able to override the tracing setting in theExampleApplication’sweb.configfile and enable the local<trace>

element, thereby overriding the settings presented in Listing 31-25

However, if you had written the attribute asallowOverride = "false"in the<location>section of

themachine.configfile, theweb.configfile forExampleApplicationis 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

Trang 10

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 aretrue,false, orreadonly Thereadonlyvalue 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 thevaluetofalsein the application’sweb.configfile

❑ 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 anIFRAMEon the client, and IE redraws only the sections of the

page that have changed By default, this option is set tofalse 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 toSystem.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 isSystem.Web.UI.UserControl You can override the default

option using this element

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

TỪ KHÓA LIÊN QUAN