Добавил:
Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:

Pro ASP.NET 2.0 In CSharp 2005 (2005) [eng]

.pdf
Скачиваний:
104
Добавлен:
16.08.2013
Размер:
29.8 Mб
Скачать

758 C H A P T E R 2 2 W I N D O W S A U T H E N T I C AT I O N

Figure 22-4. Kerberos authentication and tickets

If the server can decrypt and validate the session ticket received from the client successfully, the communication session is established. Both the client and the server use the previously generated session key for encrypting the communication traffic. As soon as the session ticket has expired, the whole operation takes place again.

Every ticket—session tickets and ticket-granting tickets—are equipped with capabilities. For example, they can impersonate the client user on the server or delegate the client’s identity to another server. If the client and the KDC do not include these capabilities into the ticket, such features just don’t work. For this purpose, the user and the server need additional permissions, as you will see in the “Impersonation” section of this chapter.

We’ll discuss the basic concepts of NTLM and Kerberos so you can understand the necessary configuration steps for making impersonation and delegation work. In most cases, if something doesn’t work with impersonation (or delegation), it’s because the domain controller or the KDC is incorrectly configured (if you are not using Active Directory) or because the expiration date of the ticket is not set appropriately (it should not be set too long but not too short either).

C H A P T E R 2 2 W I N D O W S A U T H E N T I C AT I O N

759

Although covering these topics in great detail requires an entire book, this overview will allow you to understand how the protocol works and what the requirements for different usage scenarios are.

Implementing Windows Authentication

To use Windows authentication in an ASP.NET application and have access to the user identity in ASP.NET, you need to take three steps:

1.Configure the type of Windows authentication using IIS Manager.

2.Configure ASP.NET to use the IIS authentication information using the web.config file.

3.Restrict anonymous access for a web page, a subdirectory, or the entire application.

The following sections describe these steps.

Configuring IIS

Before you can use Windows authentication, you need to choose the supported protocols by configuring the virtual directory. To do so, start IIS Manager (select Settings Control Panel Administrative Tools Internet Information Services). Then right-click a virtual directory or a subdirectory inside a virtual directory, and choose Properties. Select the Directory Security tab, which is shown in Figure 22-5.

Figure 22-5. Directory security settings

Click the Edit button to modify the directory security settings. Enable the supported protocols in the Authenticated access box in the bottom half of the window. If you enable Basic authentication, you can also set a default domain to use when interpreting the user credentials. (The user can also log into a specific domain by supplying a user name in the format DomainName\UserName.) In the example in Figure 22-6, support is enabled for integrated Windows authentication and anonymous access.

760 C H A P T E R 2 2 W I N D O W S A U T H E N T I C AT I O N

Figure 22-6. Directory authentication methods

Note If you allow anonymous access, you can also set the Windows user account that IIS will use automatically. However, this user account has very little effect and is mostly a holdover from classic ASP. In classic ASP, this account would be used to execute all code. In ASP.NET, a fixed account (typically ASPNET) is used to execute code, because more privileges are required in order to successfully compile and cache web pages.

If you enable more than one authentication option, the client will use the strongest authentication method it supports as long as anonymous access is not enabled. If anonymous access is enabled, the client will access the website anonymously. This means if you want to force clients to log in, you need to take one of two steps:

Remove the Anonymous access check box.

Add authorization rules to the web.config file that explicitly deny anonymous users from accessing a specific page, subdirectory, or application.

Authorization rules are described briefly in the section “Denying Access to Anonymous Users” and in more detail in Chapter 23.

Note If you remove integrated Windows authentication from your virtual directory, you won’t be able to debug your web application. That’s because Visual Studio .NET uses this protocol to authenticate you when you compile and run an application in the development environment.

Configuring ASP.NET

Once you’ve configured IIS, the authentication process happens automatically. However, if you want to be able to access the identity information for the authenticated user, you need to configure the web.config file to use Windows authentication, as shown here:

C H A P T E R 2 2 W I N D O W S A U T H E N T I C AT I O N

761

<configuration>

<system.web>

<!-- Other settings omitted. -->

<authentication mode="Windows"/>

</system.web>

</configuration>

This tells ASP.NET that you want to use the Windows authentication module. The WindowsAuthenticationModule HTTP module will then handle the Application_AuthenticateRequest event.

Denying Access to Anonymous Users

As described earlier, you can force users to log on by modifying IIS virtual directory settings or by using authorization rules in the web.config file. The second approach is generally preferred. Not only does it give you more flexibility, but it also makes it easier to verify and modify authorization rules after the application is deployed to a production web server.

Chapter 23 describes authorization in detail. For now, you’ll consider only the simple technique of denying access to all unauthenticated users. To do this, you must use the <authorization> element of the web.config file to add a new authorization rule, as follows:

<configuration>

<system.web>

<!-- Other settings omitted. --> <authorization>

<deny users="?" />

</authorization>

</system.web>

</configuration>

The question mark (?) is a wildcard character that matches all anonymous users. By including this rule in your web.config file, you specify that anonymous users are not allowed. Every user must be authenticated using one of the configured Windows authentication protocols.

Accessing Windows User Information

One of the nice things about Windows authentication is that no login page is required. When the user requests a page that requires authentication, the browser transmits the credentials to IIS. Your web application can then retrieve information directly from the User property of the web page.

Here’s an example that displays the currently authenticated user:

if (Request.IsAuthenticated)

{

// Display generic identity information. lblInfo.Text = "<b>Name: </b>" + User.Identity.Name; lblInfo.Text += "<br><b>Authenticated With: </b>"; lblInfo.Text += User.Identity.AuthenticationType;

}

This is the same code you can use to get information about the current identity when using forms authentication. However, you’ll notice one slight difference. The user name is always in the form DomainName\UserName or ComputerName\UserName. Figure 22-7 shows an example with a user account named Matthew on the computer FARIAMAT.

762 C H A P T E R 2 2 W I N D O W S A U T H E N T I C AT I O N

Figure 22-7. Displaying user information

The WindowsPrincipal Class

As you’ve learned in the past two chapters, the User property returns an IPrincipal object. When you use Windows authentication, this is an instance of the WindowsPrincipal class. The WindowsPrincipal class provides access to a WindowsIdentity object through the Identity property.

The WindowsPrincipal class implements three overloads of IsInRole() that all check whether the user is in a specified Windows user group. The required IsInRole(string) overload is implemented so that it accepts the name of the user group to be checked. IsInRole(int) expects an integer RID (role identifier) that refers to a user group. Finally, an overload is provided that expects a member of the WindowsBuiltInRole enumeration, which provides a list of predefined Windows account types (such as Guest, Administrator, and so on). You can find the WindowsPrincipal, WindowsIdentity, and WindowsBuiltInRole types in the System.Security.Principal namespace.

Here’s a simple example that tests whether the user is in a predefined Windows role:

if (Request.IsAuthenticated)

{

lblInfo.Text = "<b>Name: </b>" + User.Identity.Name; WindowsIdentity principal = (WindowsPrincipal)User; lblInfo.Text += "<br><b>Power user? </b>"; lblInfo.Text += principal.IsInRole(

WindowsBuiltInRole.PowerUser).ToString();

}

Note that you must cast the User object to a WindowsPrincipal in order to access this Windowsspecific functionality. Figure 22-8 shows the result.

Figure 22-8. Testing group membership

C H A P T E R 2 2 W I N D O W S A U T H E N T I C AT I O N

763

Table 21-1 lists all the possible roles provided through the WindowsBuiltInRole enumeration. You can also test for membership with any arbitrary group you’ve created. Chapter 23 discusses this technique.

Table 21-1. Values for the WindowsBuiltInRole Enumeration

Role

Description

AccountOperator

Users with the special responsibility of managing the user accounts on a

 

computer or domain.

Administrator

Users with complete and unrestricted access to the computer or domain.

BackupOperator

Users who can override certain security restrictions only as part of backing

 

up or restoring operations.

Guest

Like the User role but even more restrictive.

PowerUser

Similar to Administrator but with some restrictions.

PrintOperator

Like a User but with additional privileges for taking control of a printer.

Replicator

Like a User but with additional privileges to support file replication in a

 

domain.

SystemOperator

Similar to Administrator but with some restrictions. Generally, system

 

operators manage a computer.

User

Users are restricted accounts that are prevented from making system-wide

 

changes.

 

 

The WindowsIdentity Class

You can access some additional information about the currently authenticated user by casting the general identity object to a WindowsIdentity object. WindowsIdentity provides a number of additional members, as described in Table 21-2.

Table 21-2. Additional Members of the WindowsIdentity

Member

Description

IsAnonymous

This property returns true if the user is anonymous (has not been

 

authenticated).

IsGuest

This property returns true if the user is using a Guest account. Guest

 

accounts are designed for public access and do not confer many privileges.

IsSystem

Returns true if the user account has the Act As Part of the Operating System

 

permission, which means it is a highly privileged system account.

Groups

Retrieves a collection that contains instances of SecurityIdentifier, which

 

returns the SID values for the groups the user is in.

Token

Returns the operating system token for the identity.

Owner

Gets the SID for the token owner.

User

Gets the user’s SID. For example, you can use this SID if you want to modify

 

permissions for this user on ACLs through the classes provided in the

 

System.Security.AccessControl namespace.

Impersonate()

This method instructs ASP.NET to run the following code under the

 

corresponding Windows account. You’ll learn much more about

 

impersonation in the next section.

Continued

764C H A P T E R 2 2 W I N D O W S A U T H E N T I C AT I O N

Table 21-2. Continued

Member

Description

GetAnonymous()

This static method creates a WindowsIdentity that represents an

 

anonymous user.

GetCurrent()

This static method creates a WindowsIdentity that represents the identity

 

tied to the current security context (the user whose identity the current

 

code is running under). If you use this method in an ASP.NET application,

 

you’ll retrieve the user account under which the code is running, not the

 

user account that was authenticated by IIS and is provided in the User

 

object.

 

 

The following code displays extra Windows-specific information about the user:

if (Request.IsAuthenticated)

{

lblInfo.Text = "<b>Name: </b>" + User.Identity.Name;

WindowsIdentity identity = (WindowsIdentity)User.Identity; lblInfo.Text += "<br><b>Token: </b>";

lblInfo.Text += identity.Token.ToString(); lblInfo.Text += "<br><b>Guest? </b>"; lblInfo.Text += identity.IsGuest.ToString(); lblInfo.Text += "<br><b>System? </b>"; lblInfo.Text += identity.IsSystem.ToString();

}

Figure 22-9 shows the result.

Figure 22-9. Showing Windows-specific user information

Impersonation

Everything that ASP.NET does is executed under a Windows account. By default, this identity is the account ASPNET (in IIS 5), but it can be configured through the machine.config file, as described in Chapter 2. As each page request is processed, the configured identity determines what ASP.NET can and cannot do.

Impersonation provides you with a way to make this system more flexible. Instead of using a fixed account for all users, web pages, and applications, you can temporarily change the identity that ASP.NET uses for certain tasks. This process of temporarily assuming the identity of another Windows account is impersonation.

C H A P T E R 2 2 W I N D O W S A U T H E N T I C AT I O N

765

One common reason to use impersonation is to differentiate the permissions given to different web applications on the same computer. In this case, you configure impersonation to use a specific, fixed account for each web application. Another potential reason to use impersonation is to use the permissions that are defined for the currently authenticated user. This means the actions ASP.NET performs will be limited according to the person who is using the application. For example, your web server might be set up with a number of personalized directories, one for each user. By impersonating the user in your web application, you ensure that your application cannot inadvertently give the user access to any files except the ones in that user’s directory. If you attempt to access a restricted file, the Windows operating system will intervene, and an exception will be raised in

your code.

Note Impersonation does not give you the ability to circumvent Windows security. You must still have the credentials for the user you want to impersonate, whether you write them into your code or a user provides them at runtime.

ASP.NET has two types of impersonation. Configured (web.config) impersonation allows you to specify that page requests should be run under the identity of the user who is making the request. Programmatic impersonation gives you the ability to switch to another identity within the code and switch back to the original identity when a specific task is finished. You’ll learn about both of these techniques in the following sections.

Impersonation in Windows 2000

To impersonate other users when running on Windows 2000, the account that does the impersonation must have the Act As Part of the Operating System permission. This permission is not required on Windows XP and later.

To use impersonation, you must specifically add this permission to the ASPNET account. You can perform this administrative task using the Local Security Policy tool. Select Control Panel Administrative Tools, and select Local Security Policy. Then browse to the Local Policies User Rights Assignment node. You’ll see a list of settings, as shown in Figure 22-10.

Figure 22-10. Reviewing user rights assignments

766 C H A P T E R 2 2 W I N D O W S A U T H E N T I C AT I O N

Double-click the Act As Part of the Operating System entry, and select Add User or Group. This displays a dialog box where you can explicitly give this permission to an account. In the text box at the bottom of the window, enter the account name ASPNET, as shown in Figure 22-11.

Figure 22-11. Assigning the permission to ASPNET

Finally, click OK to confirm your action and add this permission to the ASPNET account.

Tip This permission doesn’t need to be assigned to the local system account, which always has it. As a result, if you’ve configured ASP.NET to use the local system account, you don’t need to perform any additional configuration steps.

Impersonation on Windows XP

In its default configuration, impersonation works on Windows XP workstations. Fortunately, you even don’t need to apply a high-level privilege such as the Act As Part of the Operating System privilege to a low-privileged account such as the ASP.NET user. Windows XP (and Windows Server 2003) supports a separate privilege for impersonation, as shown in Figure 22-12, which you have to assign to the account under which your worker process is running.

Figure 22-12. The Impersonate a Client After Authentication privilege

C H A P T E R 2 2 W I N D O W S A U T H E N T I C AT I O N

767

By default the ASP.NET worker process account (the ASPNET user) has this privilege, so you don’t need to perform any extra configuration steps.

Impersonation and Delegation on Windows Server 2003

When using Windows Server 2003 as a stand-alone server, you have to assign the Impersonate a Client After Authentication privilege to the account of the application pool, as is the case for the worker process account on Windows XP. The local IIS worker process group (IIS_WPG) and the local service and network service account have this privilege by default. Therefore, you don’t need to configure anything if you use a network service or local service or if you create a custom account and add it to the IIS_WPG group.

But delegation is different. As mentioned previously, delegation means that a server that has authenticated the client can pass the client’s authentication ticket to another server in this network. This means that this server (and therefore your application) acts on behalf of the client across the network. Figure 22-13 shows this in detail.

Figure 22-13. Identity flows across network hops

In Figure 22-13, you can see the big difference of impersonation. While impersonation takes place on the local machine only, delegation brings the concept of impersonation to calls across the network. Of course, if every server could do that in an uncontrolled fashion, this feature would

definitely lead to a security risk. Therefore, Windows provides you with a way to specify which computer is trusted for delegation. By default no computer in the network except the domain controller is trusted for delegation. In Figure 22-13, the server you would configure for delegation would be the Web Application Server, as this is the one that needs to pass the credentials onto the next server.

You can configure delegation through the Active Directory Users and Computers management console on your domain controller. First, you have to open the Computers node, and then select the properties of the computer you want to configure for delegation. If you are running your domain with Windows Server 2003 at a functional level (which implies you don’t have any Windows 2000 or older machines in your network), you can use constrained delegation, as shown in Figure 22-14.

If you are running the application in domains with Windows 2000 servers, you can configure the Trust for Delegation setting on the General tab of the server’s properties page. Figure 22-15 shows the settings if you are running your domain with Windows 2000 (functional level).