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

Professional ASP.NET Security - Jeff Ferguson

.pdf
Скачиваний:
28
Добавлен:
24.05.2014
Размер:
13.26 Mб
Скачать

The ASP.NET Security Framework

Representing User Identities

The Identity object is used to represent the current user's identity. This provides little or no security context (other than username for user-specific permissions). The Identity object is used for identifying a user, and is a key player in .NET personalization and customisation solutions.

The Ildentity Interface

Like the IPrincipal interface, the Ildentity interface is used to provide consistency in any authentication schema we use, whether Forms authentication, Passport authentication, Windows authentication, or a custom authentication schema. The Ildentity interface defines the basic structure of an Identity object: in other words, the Ildentity is implemented in a class that will represent the current user.

All Identity objects must implement Ildentity. When implementing Ildentity, the class must override the three properties defined by the interface:

Q AuthenticationType (String)

Gets the type of authentication used (Forms, Passport, NTLM (NT LAN Manager), or a custom authentication type).

Q IsAuthenticated(Boolean)

Gets a value that indicates whether the user has been authenticated.

Q Name (String)

Gets the name of the current user.

The following example shows a Customldentity class that implements the Ildentity interface:

using System;

using System.Security.Principal;

namespace Chapter03.Components

public class Customldentity : Ildentity

//Constructor takes only a Name argument public Customldentity(String name)

this._name = name;

 

 

 

//Overloaded constructor takes

a Name

and //an AuthenticationType

argument

 

public Customldentity (String name,

String

authenticationType) {

 

 

 

this._name = name;

 

 

 

this ._authenticationType

=

authenticationType;

}

private

String _authenticationType = "Custom"

public

String AuthenticationType

{

 

get

{

return _authenticationType;

}

}

private Boolean _isAuthenticated = false;

public Boolean IsAuthenticated { get

{

return _isAuthenticated;

}

}

private String _name;

public String Name { get

{

return _name;

All the code samples in this chapter are available as part of the code download (available at www.wrox.com). The sample code for this chapter is a Visual Studio .NET project that demonstrates how to implement authentication and authorization within ASP.NET.

This demonstrates a way of building a custom identity class that implements the I Identity interface. Here, we simply provided functionality for the required properties - those properties defined in the Ildentity interface. Every implementation of Ildentity must, at the very minimum, provide this functionality. Additional functionality may be added to the identity class based on the needs for the authentication schema.

There are four identity classes included in the .NET Framework:

Q System . Web . Secur i ty . Forms Identi ty

Provides a class to be used by the FormsAuthenticationModule

Q System. Web. Security. Pas sport Identity

Provides a class to be used by the PassportAuthenticationModule (cannot be inherited)

Q System. Security.

Principal .Genericldentity Represents a generic user identity

Q System. Security . Principal . Windowsldentity Represents a Windows user account

116

The ASP.NET Security Framework

The Genericldentity Class

The Genericldentity class represents a basic Identity object. This is the most basic of the identity objects and can be used for any purpose where an identity object is required. We previously saw an example using the GenericPrincipal class to represent the security context for the current user. In that example we created an instance of the Genericldentity class, which was used to construct the GenericPrincipal instance.

//Create a generic identity.

Genericldentity _userldentity = new Genericldentity("DSeven");

The Genericldentity class has an overloaded constructor that takes the user's name and the authentication type (as a String) as its arguments.

Some systems may provide more specific identity objects, such as Passportldentity or Windowsldentity. Each implementation of the Ildentity interface provides its own code for each of the exposed properties (AuthenticationType, IsAuthenticated, and Name). For example, the Windowsldentity class exposes the user's Windows account name in the Name property, while the Formsldentity class exposes the name passed into it when the user is logged in as the Name property.

Security Events in the ASP.NET Page Request

Authentication and authorization are handled in a web application on each request: since web applications are inherently disconnected, a user must be authenticated and authorized on each request. Not all requests require authentication or authorization, although the related events always fire.

Some requests may require neither authentication nor authorization (in which case we pass through the events without reacting to them), while others may require only authentication, and still others may require both authentication and authorization.

The two primary events we need to deal with are the AuthenticateRequest and Author izeRequest events. These are not the only events that fire, and it is important to understand where they are in the hierarchy of events that fire. The application events fire in the order shown in the following figure (not all application events are included in this diagram - just the ones related to the authentication and authorization events).

Application. BeginRequest [HttpContext becomes available]

Application. AuthenticateRequest [Populate

the Identity and Prinicpal objects]

Application.AuthorizeRequest [Handle

any custom authorization needs]

Application.AcquireRequestState [Session state becomes accessible]

Note that session state ID is not accessible until after the authorization and authentication events have fired. This prevents us from storing identity and principal information in session state, as it will not be accessible to us at the point in the process flow that we need it.

These events are handled in the Global. asax application events, and are described below.

The AuthenticateRequest Event

As we saw earlier, the AuthenticateRequest event is raised by an HttpApplication object when a request requires authentication. This means that the event is raised with each page request that is made to our ASP.NET application.

The AuthenticateRequest event is used by the authentication modules to do the work they need to do to handle authentication. This work will vary from module to module (for example, the Forms authentication module uses this event to extract user information from an encrypted cookie).

In Chapter 77, we will see how to use the AuthenticateRequest event to build our own authentication systems.

The AuthorizeRequest Event

The AuthorizeRequest event is raised after the user has been authenticated in the AuthenticateRequest event. Authorization modules use AuthorizeRequest to check whether the user is authorized for the resource they are requesting.

In Chapter 12, we will see how to use AuthorizeRequest to build our own authorization systems.

118

The ASP.NET Security Framework

The Built-in Authentication Modules

Authentication is implemented in ASP.NET through the use of authentication modules. Authentication modules consist of the code necessary to authenticate the requestor's credentials. The authentication modules give us a standard interface with which to access the security subsystem in .NET. The authentication module used is determined by the <authentication> element in the web application's configuration file (Web. conf ig). All authentication modules implement the IHttpModule interface, which provides initialization and disposal events to the authentication module.

Each of the four built-in authentication modules (DefaultAuthenticationModule, FormsAuthenticationModule, WindowsAuthenticationModule, and PassportAuthenticationModule) implements IHttpModule; the authentication modules are simply HTTP modules that handle the specified type of authentication.

Each module exposes an Authenticate event that can be handled in the Global. asax file. Additionally, the HttpApplication. AuthenticateRequest event fires regardless of the type of authentication used.

The DefaultAuthenticationModule

The DefaultAuthenticationModule is the simplest of the four provided authentication modules. All this module does is ensure an Authentication object is present in the current request/response context. The DefaultAuthenticationModule exposes one public event: Authenticate.

The Authenticate event can be handled by creating a new

Def aultAuthenticationEventHandler in the Global. asax code. This event fires after the HttpApplication. AuthenticateRequest event, but only when the current user identity is not known. You can provide your own custom authentication code in the event handler, and set the HttpContext. Current. User property to a new GenericPrincipal object that represents the current user.

The WindowsAuthenticationModule

The WindowsAuthenticationModule works in conjunction with Internet Information Services (IIS) authentication. This module is active when the <authentication> element in the Web. conf ig file is set to:

outhentication mode="Windows" />

When the WindowsAuthenticationModule is active an event handler named WindowsAuthentication_OnAuthenticate may be used in the Global. asax file. Within this event handler you may create an implementation of the IPrinicipal interface, such as the WindowsPrincipal class, and set it to the current User context.

See Chapter 7 for more about using Windows authentication and working with the

WindowsAuthentication_OnAuthenticate event.

The PassportAuthenticationModule

The PassportAuthenticationModule is active when the <authentication> element in the Web. conf ig file is set to:

outhentication mode= "Passport" />

The PassportAuthenticationModule provides a wrapper for the PassportAuthentication services; authentication is 'out-sourced1 to the Passport services, and cannot be overridden. When Passport Authentication is used a PassportAuthentication_OnAuthenticate event handler may be used in the Global. asax file. You may use this handler to set the current User context to an implementation of the IPrincipal interface, such as a GenericPrincipal object.

See Chapter 8 for more about using Passport authentication and working with the

PassportAuthentication_OnAuthenticate event.

The FormsAuthenticationModule

The FormsAuthenticationModule is active when the <authorization> element is set to:

outhentication mode="Forms" />

The FormsAuthenticationModule provides an authentication solution that uses cookies to retain any required authentication information across requests. This may be as little as a username or it may include additional information such as user roles. When the FormsAuthenticationModule is active, a FormsAuthentication_OnAuthenticate event handler may be used in the Global .asax file. You can use this event handler to set the current User context to a custom implementation of the IPrincipal interface, such as a GenericPrincipal object.

See Chapters 9 and 10 for more about using Forms authentication and working with the

FormsAuthentication_OnAuthenticate event.

The Built -in Authorization Modules

There are two authorization module classes included with the ASP.NET Framework: the FileAuthorizationModule class and the UrlAuthorizationModule class. Like the authentication modules, these two modules implement the IHttpModule interface. These modules are used to check and provide authorization resolution on requests based on the type of authentication being used.

G If Windows authentication is used, then the FileAuthenticationModule is brought into the process flow to provide access checks on the requested resource.

Q If an <authorization> element is provided in the Web. conf ig then the UrlAuthorizationModule is brought into the process flow to compare the current user context to the authorization restrictions.

See Chapter 72 for more about using the built-in authorization modules.

The FileAuthorizationModule

The FileAuthorizationModule is used when Windows authentication is used. This module handles the Authorization event and performs an access check on the target resource for the request token provided by IIS»This works with the system Access Control List (ACL), which defines which users and roles have access to system resources, as well as the type of access they have (Read, Write, Full).

120

The ASP.NET Security Framework

For example, if the requested resource is MyWebForm. aspx and the current user is Doug, the FileAuthorizationModule does an access check to see if Doug has read access to MyWebForm. aspx. If the Windows user account with the name Doug has read access privileges to MyWebForm.aspx, then the request is completed, otherwise it sets the Response.StatusCode property to 401 (Unauthorized) and calls HttpApplication.CompleteRequest to short circuit further event processing (HttpApplication.EndRequest still fires).

The UrIAuthorizationModule

The UrIAuthorizationModule is used whenever an <authorization> element is provided in the Web. conf ig file, regardless of the type of authentication that is being used. The UrIAuthorizationModule handles the Authorization event and evaluates any relevant authorization settings for the requested resource. It builds a merged list of allow and deny elements, starting at the nearest configuration file and proceeding up to the machine. conf ig configuration file. It then walks down each rule to do two things:

1. It compares "user" assertions to HttpContext .User. Identity

2. It invokes HttpContext .User. IsInRole to evaluate any role assertions:

The first matching rule (positive or negative) determines the outcome. If either module fails a request, it sets the Response . StatusCode property to 401 (Unauthorized) and calls HttpApplication.CompleteRequest to short circuit further event processing (although HttpApplication.EndRequest still fires).

The UrIAuthorizationModule has one special feature: it skips requests for the FormsAuthorization or PassportAuthorization login web forms. It does this by looking for HttpContext. SkipAuthorization, which is set by the authentication modules if the request is aimed at the configured login page.

Summary

Working within ASP.NET, we can utilize the .NET Framework's highly functional security features. Like many things in the world of ASP.NET, the presence of a security framework simply means that there is less work for us to do to implement a variety of web application authentication and authorization options. The .NET Framework provides three different types of authentication providers, Windows authentication, Passport authentication, and Forms authentication. Additionally the framework includes all of the necessary interfaces and classes to build our own authentication and authorization system.

In this chapter we looked at the following aspects of using ASP.NET authentication and authorization:

G

What the ASP.NET security framework provides Q

The authentication providers that

come as part of .NET G

The Identities and Principals within the security context G

How authentication modules work G

How authorization modules work

 

 

 

 

1O1

Windows Authentication

One option for authentication in ASP.NET is to hand over responsibility for authentication to Internet Information Services (IIS). IIS passes ASP.NET a Windows user account with each request it sends for processing. If IIS is set up to require users to log in, this account will refer to the user making the request. Because this authentication option involves Windows user accounts, it is known as Windows authentication and is provided by the Windows authentication module.

Why Would We Use Windows Authentication?

There are three main reasons why we would want to use Windows authentication:

It involves little work on our part

Integration with IIS security

Integration with Windows client machines

The first reason is quite simple – using Windows authentication hands over the responsibility for authentication to IIS so we do not have to implement that functionality ourselves. We let IIS authenticate users and then make use of the user information that IIS provides.

The second reason we might want to use Windows authentication is that it means that our web site authentication is fully integrated with IIS security. We control access to files through windows file access permissions and user accounts are managed through the normal tools.

Chapter 7

The final, and main, reason for using Windows authentication is that using IIS for authentication means that it is possible to provide 'invisible' authentication when users are logged in to Windows machines. This is ideal in situations such as intranets where we do not want the user to have to enter their username and password when they enter the intranet site – we just pick up the identity that has already been authenticated.

So why would we not want to use Windows authentication?

Tied to Windows users

Tied to Windows client machines

Lack of flexibility

The first problem is that Windows authentication relies on the users we are authenticating having valid Windows accounts. We may well not want to grant users of a web site Windows accounts on our web servers.

The second problem is that some of the authentication methods that IIS uses rely on the user having compatible software on their client machine. This limits our ability to use Windows authentication for users who are using non-Microsoft client software.

The final main problem is that Windows authentication does not give us much control over authentication. We hand the responsibility for authentication to IIS so there is not much we can do to change the way that it works.

How Does Windows Authentication Work?

Just like all other Windows processes, IIS must make an association between an authenticated user requesting a page from its virtual directory store and that user's equivalent Windows account. For those requests that IIS treats as "anonymous" requests (where a user has not entered a username and password), the IUSR account reserved as the account for which IIS will execute all server-side processing is used. To Windows, it appears as though IIS is performing a set of tasks on behalf of the IUSR account for the machine on which IIS is installed.

For pages within sites that have been restricted from anonymous users, IIS performs one of the built-in authentication functions to obtain account information from the client. We will discuss these authentication methods in the following sections. IIS hands the account information it has obtained to Windows so that the account that matches the provided data can be attached to the executing processes required to complete a given HTTP request.

IIS uses one of three possible authentication strategies to authenticate each request it receives:

Basic Authentication – the username and password are passed as clear text

Digest Authentication – the username and password are protected with cryptographic techniques

Integrated Windows Authentication – the identity of a user already logged in to Windows is passed automatically, without the need for a username and password to be entered

We'll discuss these in greater detail now.

124

Windows Authentication

Basic Authentication

Perhaps the most widely supported authentication methodology, Basic Authentication serves as a means for Internet application authentication that nearly any web browser supports. During Basic Authentication IIS obtains logon information from an HTTP client via a familiar dialog box that obtains the username and password information from the web client.

After a user provides this information, the data itself is transmitted to the web server (in this case localhost). Once IIS receives the authentication data it is used to attempt to log in to a corresponding Windows account. If an account is located in Windows that matches this data, and the account is allowed access to this particular file or virtual directory, the request is associated with the Windows account and an appropriate response – in most cases, the HTML content rendered by the web server – is returned to the client.

The process of enabling an IIS virtual directory with the Basic Authentication is straightforward, thanks to a simple Windows interface. By using the Microsoft Management Console (MMC) snap-in for Internet Information Services, any virtual directory or entire web site can be set up to authenticate users via Basic Authentication. To do so, locate the virtual directory you wish to secure, right-click on it, and select properties.

125

Соседние файлы в предмете Программирование