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

Tài liệu ASP.NET 1.1 Insider Solutions- P12 ppt

50 324 0
Tài liệu đã được kiểm tra trùng lặp

Đ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

Tiêu đề Building a Custom Authentication Module
Trường học Unknown University
Chuyên ngành ASP.NET
Thể loại document
Năm xuất bản Unknown Year
Thành phố Unknown City
Định dạng
Số trang 50
Dung lượng 515,6 KB

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

Nội dung

Before the module can be used, you need to ensure that no other authentication modules areactive by setting the element of the web.configfile appropriately: After you have done this, you

Trang 1

Building a Custom Authentication Module

Authentication is the process of identifying users Authentication modules use evidence in each

request made to the application to identify which user is making the request The tion modules that ship with ASP.NET use as their evidence encrypted cookies in the request(forms authentication and Passport authentication) and evidence provided by IIS (Windowsauthentication)

authentica-What Is an Authentication Module?

In code terms, an authentication module is an HTTP module that handles the AuthenticateRequest

event of the HttpApplicationobject When the event fires, the authentication module checks theevidence associated with the request and populates the Context.Userintrinsic object with anappropriate IPrincipalobject (that is, an object of a class that implements the IPrincipalinter-face) The authorization module then uses Context.Useras the basis for deciding whether therequest should be authorized The rest of the application code is then able to access whateverdata is stored in the IPrincipalobject

It is actually pretty rare that you need to replace the standard authentication modules with acustom solution Usually you can solve your problems by customizing one of the existingmodules Forms authentication, as you saw in Chapter 13, is particularly suitable for suchmanipulation

One situation in which a custom authentication module is useful is when you want to identifyaccess to an application according to which machine is trying to access the application ratherthan according to which specific user is making the request For example, if you have anintranet application running on a closed network in a shopping mall, you might want to iden-tify which client machines are used to make requests in order for the application to behavedifferently (For example, the application might show special offers appropriate to stores nearthe client machine that is being used, or the map might be able to show a “you are here” label.)There are all sorts of ways you can solve this problem One clean way is to implement a customauthentication module that uses the IP address of the client machine as the evidence forauthentication The following sections show how to build a simple HTTP module that providesthis functionality

Building a Custom Identity Class

Before you build the HTTP module itself, you need to think about the IPrincipalobject that itwill use to populate Context.User The principal represents the security context of the user Theinterface has the following members:

Identity IIdentity IsInRole(String) Boolean

Trang 2

Every IPrincipalobject will store an IIdentityobject that represents the identity of the ticated user and will allow you to check whether the user is in a particular role.

authen-You can build a custom class that implements IPrincipal, but there is rarely any need to do so;

System.Security.Principal.GenericPrincipaldoes the job in the vast majority of cases

GenericPrincipalprovides a constructor that takes an IIdentityobject and an array of strings forthe roles It simply stores the roles internally and checks against them when IsInRoleis called

Most authentication approaches can use GenericPrincipal The exception is Windows cation, which needs to check roles against the user’s Windows roles rather than against a set ofroles stored by the principal object It therefore defines a different IPrincipalimplementation,WindowsPrincipal In the IP authentication example, GenericPrincipalwill do just fine However,you should create a custom identity class that implements IIdentity The reason becomes clearwhen you look at the members required by the IIdentityinterface:

AuthenticationType String IsAuthenticated Boolean

The identity needs to return the type of authentication used to create it, so a new identity class

is needed for each authentication module

The following is the code for an identity class for the IP authentication module:

Public Class IPIdentityImplements System.Security.Principal.IIdentityPrivate _IP As String = Nothing

Public Sub New(ByVal ip As String)_IP = ip

End Sub

‘do not allow an IPIdentity to be created without an IP addressPrivate Sub New()

End SubPublic ReadOnly Property AuthenticationType() As String _Implements System.Security.Principal.IIdentity.AuthenticationTypeGet

Return “IP”

End GetEnd PropertyPublic ReadOnly Property IsAuthenticated() As Boolean _Implements System.Security.Principal.IIdentity.IsAuthenticated

Trang 3

‘An IP Identity will only be used when authentication is successfulReturn True

End GetEnd PropertyPublic ReadOnly Property Name() As String _

Implements System.Security.Principal.IIdentity.NameGet

Return _IPEnd GetEnd PropertyEnd ClassYou store the IP address of the machine that is making the request in a private field A construc-tor is provided to allow a new IPIdentityobject to be created from an IP address, but you markthe default constructor as private so it cannot be used

The members required by IIdentityare each provided AuthenticationTypereturns “IP”

IsAuthenticatedreturns true; you will be using IPIdenityonly with authenticated requests Namereturns the IP address string

This is a pretty minimal IIdenityimplementation You can add other data to the identity class.For example, FormsIdentityprovides access to the forms authentication ticket

Building the HTTP Module

Now that you know what the IP authentication module is going to populate Context.Userwith,you can press on and build the HTTP module that will implement it (see Listing 14.1)

LISTING 14.1 An HTTP Module Implementation for IP-Based AuthenticationImports System.Security.Principal

Public Class IPAuthenticationModuleImplements IHttpModule

Public Sub Dispose() Implements System.Web.IHttpModule.Dispose

‘we have no resources to dispose ofEnd Sub

Public Sub Init(ByVal context As System.Web.HttpApplication) _

Implements System.Web.IHttpModule.Init

‘handle the AuthenticateRequest of the applicationAddHandler context.AuthenticateRequest, AddressOf Me.AuthenticateEnd Sub

Trang 4

Public Sub Authenticate(ByVal sender As Object, ByVal e As EventArgs)Dim application As HttpApplication = CType(sender, HttpApplication)

‘create identity and principal objectsDim identity As New IPIdentity(application.Request.UserHostAddress)Dim principal As New GenericPrincipal(identity, New String() {})

‘attach the principal to the application contextapplication.Context.User = principal

End SubEnd Class

You don’t need to do anything in the Disposemethod because you use no resources that requiredisposal You have to include it, though, because it is required by the IHttpModuleinterface

In the Initmethod, you bind the Authenticatemethod of this class to the AuthenticateRequestevent of the application In the Authenticatemethod, you simply use the IP address of therequest (Request.UserHostAddress) to create an IPIdentityobject, which is then used to construct

a GenericPrincipalinstance that is stored in Context.User

Before the module can be used, you need to ensure that no other authentication modules areactive by setting the <Authentication>element of the web.configfile appropriately:

After you have done this, you can access the IP address of the client through Context.User

Identity.Name (This is not very impressive, admittedly, because you can access it throughRequest.UserHostAddressanyway.) More interestingly, you can use URL authorization by specify-ing the IP addresses as the usernames:

<authorization>

<allow users=”127.0.0.1” />

LISTING 14.1 Continued

Trang 5

Running Authentication Modules in Tandem

The built-in authentication modules in ASP.NET can only be used one at a time, but there is noreason you cannot have additional custom authentication modules running on top of the built-

in modules

For example, you might want to use forms authentication to allow administrators to sign in tothe system but use the IPAuthenticationModuleimplementation that you built in the previoussection to identify the client machine for users who are not authenticated by the forms authen-tication module

The important thing to do if you want to use more than one module together is to ensure thatthey do not clash with each other You can change the IPAuthenticationModuleimplementation

so that it will populate the Context.Userobject only if it has not already been populated byanother authentication module (see Listing 14.2)

LISTING 14.2 Adapting IPAuthenticationModuleto Allow It to Work with Other ModulesPublic Sub Authenticate(ByVal sender As Object, ByVal e As EventArgs)

Dim application As HttpApplication = CType(sender, HttpApplication)

‘check that the user has not been created or is not authenticated

If application.Context.User Is Nothing _OrElse Not application.Context.User.Identity.IsAuthenticated Then

‘create identity and principal objectsDim identity As New IPIdentity(application.Request.UserHostAddress)Dim principal As New GenericPrincipal(identity, New String() {})

‘attach the principal to the application contextapplication.Context.User = principal

End IfEnd Sub

Trang 6

The IPAuthenticationModuleimplementation will then happily coexist with the forms authentication module When forms authentication does not authenticate the user, theIPAuthenticationModuleimplementation will populate the Context.Userobject When formsauthentication does pick up a ticket and authenticate the user, the IPAuthenticationModuleimple-mentation will do nothing.

This system will work best when forms authentication is set up to support role-based tion, so that the administrators or other privileged users can be placed in a role

authoriza-The example shown here is very simple, but it shows all the features that are required from anauthentication module If you have some authentication requirements that are not served bythe default modules, you should be able to build a custom module to do the job

Building a Custom Authorization Module

Authorization is the process of deciding whether the current user has permission to access the

resource that he or she requested The authorization modules that ship with ASP.NET decidewhether the resource can be accessed by either checking Windows access control lists (fileauthorization) or checking the <authorization>element of the configuration file (URL authoriza-tion)

There are lots of other possibilities for authorizing the requests of users For example, you mightallow access only at certain times, you might require users to have been registered with theapplication for a certain amount of time before accessing some content, or you might assigneach user credits that he or she can use to access pay-per-view content Or you might use asingle-page application architecture and want to authorize based on the URL parameters of therequest

The best way to implement custom authorization behavior is by creating an authorizationmodule Like authentication modules, authorization modules are HTTP modules (although theyhook into the AuthorizeRequestevent rather than the AuthenticateRequestevent)

Listing 14.3 shows a simple authorization module that checks the expiration date in a customidentity against the current date

LISTING 14.3 A Custom Authorization ModulePublic Class ExpirationAuthorizationModuleImplements System.Web.IHttpModulePublic Sub Dispose() Implements System.Web.IHttpModule.Dispose

‘nothing to dispose ofEnd Sub

Public Sub Init(ByVal context As System.Web.HttpApplication)

➥Implements System.Web.IHttpModule.InitAddHandler context.AuthorizeRequest, AddressOf Me.Authorize

Trang 7

End SubPrivate Sub Authorize(ByVal sender As Object, ByVal e As EventArgs)Dim application As HttpApplication = CType(sender, HttpApplication)

If application.Context.Request.IsAuthenticated Then

If Not application.Context.User.IsInRole(“NonExpiring”) ThenDim identity As ExpiringIdentity = _

CType(application.Context.User.Identity, ExpiringIdentity)

If identity.Expires < DateTime.Now Then

‘the users registration has expiredapplication.Context.Response.Redirect(“RegistrationExpired.aspx”)End If

End IfEnd IfEnd SubEnd Class

The infrastructure of this authorization module is very similar to that of the custom tion module discussed earlier in this chapter in the section, “What Is an Authentication

authentica-Module?”

In the Authorizeevent handler, you check whether the user is authenticated (This module isdesigned to only check for expired membership; it does not deny authorization to anonymoususers It is assumed that URL authorization would be used to do that.)

Next, you check that the user is not in the NonExpiringrole If he or she is, you do nothingmore, and the user is allowed to view the resource he or she requested If the user is not in theNonExpiringrole, you check the current date and time against the user’s expiration date and timefrom the ExpiringIdentityobject in Context.User.Identitiy If the user has expired, you redirectthe response to the “registration expired” page

You may be wondering what the ExpiringIdentityclass looks like It is shown in Listing 14.4

LISTING 14.4 The ExpiringIdentityClassPublic Class ExpiringIdentity

Implements System.Security.Principal.IIdentityPrivate _Username As String

Private _MembershipExpires As DateTimePublic Sub New(ByVal username As String, ByVal expires As DateTime)

LISTING 14.3 Continued

Trang 8

_Username = username_MembershipExpires = expiresEnd Sub

Private Sub New()End Sub

Public ReadOnly Property AuthenticationType() As String _Implements System.Security.Principal.IIdentity.AuthenticationTypeGet

Return “Custom”

End GetEnd PropertyPublic ReadOnly Property IsAuthenticated() As Boolean _Implements System.Security.Principal.IIdentity.IsAuthenticatedGet

Return TrueEnd GetEnd PropertyPublic ReadOnly Property Name() As String _Implements System.Security.Principal.IIdentity.NameGet

Return _UsernameEnd Get

End PropertyPublic ReadOnly Property Expires() As DateTimeGet

Return _MemberShipExpiresEnd Get

End PropertyEnd Class

Running Authorization Modules in Tandem

As with authentication modules, you can run multiple authorization modules at the same time

You do not have to worry about clashing authorization modules as you do with authenticationmodules If any of the authorization modules in the chain results in failed authorization, it willtake action ahead of any other modules This is as it should be; when it comes to security, youshould always pay attention to the test that fails rather than to the test that passes

LISTING 14.4 Continued

Trang 9

The example shown in Listing 14.4 is designed to work in tandem with URL authorization URLauthorization would be used to keep anonymous users from using the application, whereasExpirationAuthorizationModuleimplementation would be used to deal with users whose registra-tions have expired.

Trust Levels

By default, ASP.NET applications run at full trust This means that the NET Framework places

no limitations on what they can do, aside from the limitations imposed by the operating system

on the account that ASP.NET runs under This is not a huge problem if you trust all the ers who write code for all the ASP.NET applications that run on your server, but what if you

develop-do not?

Also, running all applications at full trust breaks the principle of least privilege—the idea thatfor the best possible security, code should be allowed only the permissions that it absolutelyneeds

The solution is to force applications to run at less than full trust ASP.NET ships with four ent levels of trust and allows you to configure your own trust levels if you need to specify aparticular set of permissions

differ-Using One of the Preconfigured Trust Levels

In addition to the full-trust mode that places no restrictions, four trust levels are provided withASP.NET (see Table 14.1)

TA B L E 1 4 1The Four Trust Levels Provided with ASP.NETTrust Level Main PermissionsMinimal Only the bare minimum that are required for ASP.NET to functionLow Very limited access to the file system

Medium Limited read/write access to the file system; some other permissionsHigh Full access to the file system; most other permissions

Remember that the permissions granted by these trust levels do not allow the ASP.NET useraccount to access anything that it does not have operating system permissions for Trust levelscan only impose additional restrictions; they can never remove existing operating system restric-tions

Let’s look at each trust level in more detail to see what permissions the levels provide

The Minimal Preconfigured Trust LevelThe minimal trust level only grants the permissions that are absolutely required for an ASP.NETapplication to run

Trang 10

An ASP.NET application running at this trust level will not be able to do a lot It can’t do anyfile system input/output work, can’t do any data access, can’t access isolated storage, can’t accessthe registry, and can’t execute any code that requires reflection In fact, applications at this trustlevel can’t really do anything apart from read the HTTP request and write to the HTTP response.Another restriction when running at this trust level (and low trust) is that it does not allowdebugging Attempting to run an application that is configured for debugging at this trust levelwill result in an error message For this reason, you have to appropriately set the <compilation>

element in the web.configfile for applications that will run at minimal or low trust:

<compilation defaultLanguage=”vb” debug=”false” />

The Low Preconfigured Trust LevelThe low trust level does not allow very many more permissions than minimal trust At thislevel, the application can read (but not write) files that are within its application directory, and

it can read and write isolated storage with a quota of 1MB

Note that the low trust level has the same limitation on debugging that the minimal trust levelhas: If you configure an application with low trust for debugging, you will get an error

The Medium Preconfigured Trust LevelCompared to the minimal and low trust levels, quite a few additional permissions are added atthe medium trust level Debugging is now allowed You can read and write files within theapplication directory You also have access to isolated storage with an effectively unlimitedquota An application can access a SQL Server database through the SqlClientclasses and caneven print to the default printer

At this level, an application also gets read access to the following environment variables:

The medium trust level contains the permissions that most ASP.NET applications need to run

The High Preconfigured Trust Level

At high trust, an application gets unrestricted access to most resources, including the file system,isolated storage, environment variables, the registry, and sockets An application also gains theability to generate dynamic assemblies by using Reflection.Emit

Trang 11

Remember, though, that ASP.NET is still limited by the permissions that the account underwhich it runs has been given.

Forcing an Application to Use a Trust Level

As mentioned earlier in this chapter, the default trust level for ASP.NET applications is full trust.You can see this by finding the appropriate section of the machine.configfile:

<location allowOverride=”true”>

<system.web>

<securityPolicy>

<trustLevel name=”Full” policyFile=”internal”/>

<trustLevel name=”High” policyFile=”web_hightrust.config”/>

<trustLevel name=”Medium” policyFile=”web_mediumtrust.config”/>

<trustLevel name=”Low” policyFile=”web_lowtrust.config”/>

<trustLevel name=”Minimal” policyFile=”web_minimaltrust.config”/>

Often, though, you want to configure different trust levels for different applications This isespecially true if you want to follow the principle of least privilege and want to have each appli-cation run with only the permissions it needs

You can take a number of approaches to this You could remove the <trust>element from themachinewide <location>element and instead include a <location>element for each application

If you do this, you have to be careful to include one for each application, or you will get errors.(Every application must have a <trust>element at some level of its configuration.)

You can’t simply define a default in the machinewide <location>element and then include tional <location>elements in the machine.configfile to specify the trust levels for individualapplications You are not allowed to include the <trust>element twice in a single configurationfile

addi-If you want to configure a default and then define different trust levels for certain applications,you have to use multiple configuration files If you can’t define the settings in the machine.configfile, along with the machinewide default, and you can’t define it in the web.configfile forthe specific application, you have to use a web.configfile at the Web site level

Trang 12

The following web.configfile will, when added to the root folder of the Web server (usuallywwwroot), specify that the application called UntrustedAppthat is in the InsiderSolutionsfoldershould be run at low trust:

<?xml version=”1.0” encoding=”utf-8” ?>

<configuration>

<! configure a lower trust level for one application >

<location allowOverride=”false” path=”InsiderSolutions/UntrustedApp”>

do anything, as the low trust level does not include the WebPermissionpermission)

You could also specify a trust level for all applications in the InsiderSolutionsfolder as follows:

<?xml version=”1.0” encoding=”utf-8” ?>

<configuration>

<! configure a lower trust level for one application >

<location allowOverride=”false” path=”InsiderSolutions “>

Creating Custom Trust Levels

The trust levels that ship with ASP.NET provide a pretty good spread of permission sets, but ifyou want to have complete control over what applications are doing on your server, you need

to define your own trust levels

The best way to go about this is to start from one of the existing trust levels and use it as thebasis for your new trust level By copying its policy file and making changes, you can construct

a new trust level with just the permissions you want With this in mind, let’s take a look at thepolicy file for the medium trust level to see how the policy files are structured

The policy file for the medium trust level can be found in Windows/Microsoft NET/Framework/

[version]Config/Web_MediumTrust.config The file has an overall structure like this:

<configuration>

<mscorlib>

<security>

Trang 13

a set of 0 or more <IPermission>

elements to define the permissions in the set

</permissionSet>

</namedPermissionSets>

<codeGroup>

nested <codeGroup> elements that link code

to permission sets based on conditions:

For the purposes of changing the permissions that ASP.NET applications run with, you do notneed to change the <codeGroup>elements; you just need to add or remove permissions from the

<permissionSet>element that holds the permissions that are granted to the ASP.NET application.The Web_MediumTrust.configfile contains three permission sets: a full access set that grants unre-stricted privileges, a set that grants no privileges, and a set with the permissions that are actuallygranted to the ASP.NET application

The unrestricted privileges are granted to assemblies signed with either the Microsoft or theECMA strong name (that is, code that Microsoft or ECMA says should be trusted)

The permission set that grants no permissions is used as the default for code that is not matched

to any other permission set

Trang 14

Listing 14.5 shows the <permissionSet>element from Web_MediumTrust.configthat is granted tothe code of the ASP.NET application itself.

LISTING 14.5 Permissions from the Medium Trust Level Configuration File

Trang 15

Removing permissions from the trust level is easy: You simply need to delete the IPermissionelement for the permission you want to remove For example, if you do not want applicationsrunning at this trust level to have access to isolated storage, you would remove the element thatsets that permission:

Looking at a <SecurityClass>element from the file, you can see that you have to provide the fullnamespace and classname for the class, the assembly it is in, the version, the culture, and apublic key token:

<SecurityClass Name=”AllMembershipCondition” Description=

➥”System.Security.Policy.AllMembershipCondition, mscorlib,

➥ Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b77a5c561934e089”/>

LISTING 14.5 Continued

Trang 16

Fortunately, there is a way to generate the<SecurityClass>elements you need—by using the.NET Framework Configuration tool The tool does not allow you to edit the ASP.Net trust levelpolicy files directly, but you can add permissions to a permission set in one of the files that thetool can edit and then copy them across to the trust level file.

To use the NET Framework Configuration tool, you select Start, Control Panel, AdministrativeTools, NET Configuration Then you open Runtime Security Policy and then the User branch ofthe tree-view and click the Permission Sets branch You can then click the New Permission Setlink in the main window to create a permission set, as shown in Figure 14.1

FIGURE 14.1

Creating a permission set

in the NET FrameworkConfiguration tool

Next, you enter a name (it doesn’t really matter what name you use—you won’t be using thispermission set for anything) It would be best to give it a name and description that make itclear that this is a temporary set that you are using to create permissions and classes to copyacross to ASP.NET configuration Then you can click Next, and you will see the window whereyou can add permissions to the set (see Figure 14.2)

FIGURE 14.2

Adding permissions to a permission set

Trang 17

On the Create Permission Set window, you simply move the permissions that you want to addover to the Assigned Permissions box on the right side When a permission is added, a newwindow will open, with the relevant options for that permission This is a great way to learnwhat permissions are available and what options are available for each one.

For example, if you add the OLE DB permission, which allows access to OLE DB modules, yousee the options shown in Figure 14.3

FIGURE 14.3 Options for the OLE DB

permission

After you set the settings you want, the file will be located in Documents and settings/

[username]/Application Data/Microsoft/CLR Security Config/[version]/security.config In this

file, you will find the permission set that you have added:

Trang 18

After you have created a new trust level policy file, you need to add it to the set that is availablefor use, by editing the <securityPolicy>element of the machine.configfile:

<location allowOverride=”true”>

<system.web>

<securityPolicy>

<trustLevel name=”Custom” policyFile=”web_customTrust.config”/>

<trustLevel name=”Full” policyFile=”internal”/>

<trustLevel name=”High” policyFile=”web_hightrust.config”/>

<trustLevel name=”Medium” policyFile=”web_mediumtrust.config”/>

<trustLevel name=”Low” policyFile=”web_lowtrust.config”/>

<trustLevel name=”Minimal” policyFile=”web_minimaltrust.config”/>

The string $AppDir$is converted to the path to the application folder at runtime

You can also use the following substitutions:

$OriginHost$ - the address of the client that made a request to the application

$AppDirUrl$ - the URL of the application

$CodeGen$ - The folder where ASP.NET stores dynamically generated assemblies

$Gac$ - the Global Assembly Cache folderNote that the last three substitutions are usually used in code groups rather than in permissions

Trang 19

Recommended Use of Permissions

Table 14.2 shows all the permissions that can be used, along with some recommendations forhow to apply them

TA B L E 1 4 2The Allowed Permissions

DirectoryServicesPermission You should grant this permission if the application needs to access Active

Directory or LDAP data

DnsPermission You should grant this permission if the application needs to resolve domain

names to IP addresses This is a pretty safe permission to grant

EventLogPermission You should grant this permission if the application needs to read or write to

event logs (on the machine it is running on or another machine) Note thatthe ASP.NET account will need permission to access the event log as well

EnvironmentPermission You should grant this permission if the application needs to access

environ-ment variables It is usually advisable to grant read access only; it is veryrare that a Web application should need to set environment variables

FileIOPermission You should use this permission to allow access to files It is usually used

with the $AppDirsubstitution to allow access to the application’s ownfolder, but it can also be used to allow access to other specific locations

FileDialogPermission This permission is not really relevant to Web applications and so should not

be granted to them It allows Windows Forms applications to create openand save dialogs

IsolatedStoragePermission You should grant this permission if the application needs to use isolated

storage The AssemblyIsolatedByUseroption will allow access to the datafrom different applications (provided that they do it through the sameassembly), whereas DomainIsolatedByUserwill allow access only from theapplication that created the data

MessageQueuePermission You should grant this permission if the application needs to interact with

message queues

OleDbPermission You should grant this permission if the application needs to use OLE DB

data sources You can grant access to all data modules or list specificmodules This is a common permission to grant

PerformanceCounterPermission You should grant this permission if the application needs to read (browse)

or write (instrument) performance counters You can specify permissions forcounters on specific machines and also for specific categories of counters

on a machine

PrintingPermission It is unlikely that a Web application will need to access printers, so it is

best not to grant this permission

RegistryPermission This can be a highly dangerous permission to grant, so treat it with caution

(However, the risks are mitigated by the limitations that the operatingsystem places on the ASP.NET account.)

ReflectionPermission You should grant this permission if the application needs to be able to

perform reflection-based operations on other assemblies Quite a lot of NETFramework applications now make use of reflection, so this permission islikely to be in demand However, this permission is not required for reflec-tion within an assembly

Trang 20

SecurityPermission This permission has a myriad of options Think carefully before granting any

of these because many of them can allow code to circumvent code accesssecurity checks in one way or another

ServiceControllerPermission You should grant this permission if the application needs to connect to

Windows services in order to work The Browse option is sufficient toconnect to services If the application needs the ability to start and stopservices, it will need the Control option

SocketAccessPermission You should grant this permission if the application needs to perform

low-level networking tasks

SQLClientPermission You should grant this permission if the application needs to access SQL

Server data This is a common permission to grant

WebPermission You should grant this permission if the application needs to make Web

requests of its own This is actually quite rare (most Web applications respond

to requests rather than make their own requests) but can be useful sometimes

UserInterfacePermission This permission is typically not granted to Web applications because it is

really only relevant to Windows Forms applications

A Permission Set for Normal UseFor most ASP.NET applications, the medium built-in trust level is ideal If you want to run thingswith the least privileges (which you should where possible), you will probably want to removesome of the permissions that your application does not require

If your application does not need access to environment variables, you can safely get rid ofEnvironmentPermission

You can get rid of IsolatedStoragePermissionif your application does not use isolated storage

Most Web applications can dispense with PrintingPermission

If the application does not need to make Web requests of its own, you can remove WebPermission.Implementing all these changes in a custom trust level would leave something like the permis-sion set shown in Listing 14.6

LISTING 14.6 A Permission Set Based on the Medium Trust Level, with Unnecessary Permissions Removed

Trang 21

You can probably remove the ability for the application to discover paths because browsing thefile system is not usually a requirement for Web applications.

If your application only reads data (for example, an XML configuration file), you can remove theWrite and Append attributes, too:

Trang 22

The chapter shows how to build custom authentication modules when the modules provided byMicrosoft do not provide the features you need A sample module is presented and explained.

Custom authorization modules are also covered

Finally, the chapter looks at how NET Framework code access security can be applied toASP.NET, through trust levels The standard trust levels are explained, and the process of build-ing custom trust levels is shown

Trang 24

A

absolute positioning, 203access codes (provider-independent data), 410

dynamically instantiating classes, 410-411sample page code, 411-415

accessing

customer ID values, 96keypress information, 202-203page elements, 201-202XML configuration settings, 467-470XML resources, 438-439

Evidence class, 439Load() method, 439-441Transform() method, 441-442XmlResolver class, 439XslTransform class, 439

accessor routines

ComboBox user control property, 176-178declaring in C#, 178

IsDropDown property, 179Items property, 180Rows property, 179SelectedIndex property, 181SelectedItem property, 180-181SelectedValue property, 182-183Width property, 178

declaring in C#, 177-178exposing, 175

Trang 25

adaptive SpinBox server control, 334, 339

browser-specific output, 342-343CreateChildControls() method, 340-342internal variables, 339-340

LoadPostData() method, 343-346properties, 339-340

testing, 346-348

Add value, 401AddAttribute() method, 303AddAttributesToRender() method, 304, 309-311adding

controls, 40-41permissions, 552-553

AddNamespace() method, 454AddParsedSubObject() method, 362AddStyleAttribute() method, 303AddTable routine, 96

AddWithKey value, 401allocating applications, 495allowed permissions, 556-557Amaya, 336-337

animated GIFs (progress bars), 86apartment-threaded COM components, 168APIs (Application Program Interfaces), XML

advantages/disadvantages, 430-431cursor-style, 432

DOM, 431-432forward-only, 431serialization, 432-433

appearance properties, 257-258

applications See also utilities

ASP.NET versions, specifying, 489installing without updating mappings,489-490

runtime versions, configuring, 490-492key-generator, 517

mappings, 488-489

pools (IIS 6.0), 494-496version 1.0 running, 482, 488automatic input validation, 483-484forms authentication, 487

list control properties, 485MMIT mobile controls, 488System.Data namespaces, 486-487virtual Web

listing, 492mappings, 488-489

ASPNET account, 482ASP.NET State Service, 481aspnet_client folder, 251aspnet_regiis.exe utility

applications, updating, 490client-side script folder, installing, 492.NET Framework versions, listing, 491parameters, 490-491

runtime, 490-492Web sites, listing, 492

assemblies

machinewide installation, 164-165SpinBox, 350

asynchronous loading, 88AttachDialog() method, 269

browser-adaptive script dialogs, 277-278client-side script dialogs, 270-272modal dialog windows, 287-290

attributes

adding, 349DataKeyField, 120encyrptionKey, 487MasterPageFile, 379-380OnItemDataBound, 120TabIndex, 215validationKey, 487width, 33

Ngày đăng: 21/01/2014, 09:20