Authorization in ASP.NET


Let’s look at how authorization fits in with ASP.NET. First we’ll look at the permissions that .NET Web services themselves have and how to customize this behavior. Then we’ll look at how to use user account information to control which tasks Web services can perform. This discussion will cover the concept of user account impersonation, whereby Web services carry out tasks using the logged in account. Finally, we’ll discuss how to restrict access to Web services based on user information.

ASP.NET Process Identity

As mentioned earlier, the default behavior for ASP.NET Web services is to execute under the ASPNET account. This means that any actions you take, such as database access, file manipulation, registry modifications, and so on, are carried out under this account. This can be good or bad, depending on the way your service works. The ASPNET account has restricted access, which means you can be fairly certain that the Web service can’t do anything dangerous, but at the same time it might be tricky to get at the information you want using this account.

This isn’t necessarily a problem because, as you’ll see in a later section, you can often avoid the ASP.NET process identity account entirely. However, this can sometimes be an important problem, especially in simple services that don’t perform authentication, so we should look at how to change this process.

ASP.NET Process Identity Configuration

The machine.config file on your .NET Web server (found in \Windows\ Microsoft.NET\Framework\<Version>\CONFIG\ in default installations) contains the following element:

<processModel enable="true" timeout="Infinite" idleTimeout="Infinite"   shutdownTimeout="0:00:05" requestLimit="Infinite"   requestQueueLimit="5000" restartQueueLimit="10" memoryLimit="60"   webGarden="false" cpuMask="0xffffffff" userName="machine"   password="AutoGenerate" logLevel="Errors" clientConnectedCheck="0:00:05"   comAuthenticationLevel="Connect" comImpersonationLevel="Impersonate"   responseDeadlockInterval="00:03:00" maxWorkerThreads="20"   maxIoThreads="20"/>

The two emphasized attributes, userName and password, are responsible for setting the ASP.NET process identity account. The userName attribute can be set to machine to use the ASPNET account, SYSTEM to use the System account, or any other username you like. If a value other than machine or SYSTEM is specified, the account password must be entered in password rather than the special value AutoGenerate.

Any account specified must have the following minimum security settings:

  • Read access to the Windows\Microsoft.NET\Framework\<Version> directory as well as read/write access to the Temporary ASP.NET Files directory contained there

  • Read/write access to the Windows\Temp directory and read access to the Windows\Assembly directory (the global assembly cache)

  • Read access to the Web site root directory, typically inetpub\wwwroot for the default Web site

  • Read access to a Web application directory that will run under this account

Bear in mind, though, that modifying these userName and password settings can be dangerous. If you set the ASP.NET process identity to use the System account or a system administrator account, Web services will have permission to do pretty much anything. Even a slight misstep in your Web service code then can open the door to malicious attacks. In general, the ASPNET account is fine because when we want additional permissions it isn’t too tricky to obtain them by other means. Rather than changing this setting to a user with a slightly higher level of permissions than ASPNET, it is usually easier to simply add permissions to the ASPNET account—as long as we’re not talking about potentially lethal permissions. Giving the ASPNET account rights to write to a specific temporary directory or to an access database so data can be updated is generally fine.

To avoid exposing the username and password for a specified account in plain text, you can store these details in the registry in an encrypted format, by using the Windows API CryptProtectData function. You can then set the userName and password attributes as follows:

<processModel ...   userName="registry:HKLM\<SubKey>\,userName"   password="registry:HKLM\<SubKey>\,password"   ... />

<SubKey> refers to the key containing the two binary values userName and password, which hold the encrypted information.

Tip

If you want to store these details in the registry in an encrypted format, the aspnet_setreg.exe utility can be useful because it can encrypt the required data and add it to the registry automatically. You can download this utility from http://support.microsoft.com/default.aspx? scid=kb%3ben-us%3b329290.

Authorizing Users

Authorization typically consists of checking whether a user is a member of a certain group (such as Administrators, Group Managers, and so on) and then carrying out an action using the ASP.NET process identity or the identity of the logged-in user (if the user is mapped to a Windows user account).

Role Membership

Users who have Windows accounts can be members of Windows groups such as Administrators or Users. Other types of users can also be divided into roles or groups, either by virtue of what they are or by some custom scheme that you have devised. Either way, you can use the IPrincipal.IsInRole method to check membership.

You simply pass a string to the method and get a Boolean result, as in this code:

if (Context.User.IsInRole("Customers")) {     // do something that requires Customers permissions }

Alternatively, if you are using a WindowsPrincipal, you can use overloaded versions of this method to check for such roles, including a version that uses values from the WindowsBuiltInRole enumeration. These values include WindowsBuiltInRole.User and WindowsBuiltInRole.Administrator.

Note that checking for roles doesn’t necessarily mean that you can then carry out tasks on behalf of these roles. You are still tied to the security privileges of the ASP.NET process identity account (or lack thereof). However, one way around this restriction is to use impersonation.

Impersonation

Impersonation means running code as if it were under the account of a user other than the ASP.NET process identity. You can use impersonation to expose files and other resources that aren’t generally accessible by Web services, for example. We know that we are doing this for authenticated users only, so we can be reasonably sure that nothing bad will happen. (Of course, some resources should never be exposed except to highly trusted individuals!)

You can implement impersonation in two ways. One way is to configure it in the web.config file of a Web application or a Web service, and the other is to use code inside a Web method. The advantage of the former approach is that you don’t have to do much work at all—you just say “go ahead and use the such-and-such account to execute this service.” The latter approach is more versatile and fits in better with non-IIS authenticated services.

Let’s start by looking at the first configuration approach, which involves the use of the <identity> element. By default this element has an impersonate attribute of false:

<identity impersonate="false" />

When you set this attribute to true, you can use impersonation with whatever account has been authenticated using IIS. This can be very useful in combination with the IIS authentication methods we examined earlier.

Important

If you use anonymous access, the Web service will run under the anonymous account configured by IIS, which is IUSR_MachineName by default, not ASPNET.

Alternatively, you can use the <identity> element to specify that a specific account should be used to run the application, by using the userName and password attributes:

<identity impersonate="true" userName="Keith Chegwin"   password="PlaysPop"/>
Tip

The aspnet_setreg.exe utility we referred to earlier can also be used to encrypt username and password data for use in impersonation.

From code, we can impersonate a Windows user using the WindowsIdentity.Impersonate method, which returns a WindowsImpersonationContext object. Between the Impersonate call and a call to WindowsImpersonationContext.Undo, code will run under the impersonated account.

This is the method used in the IISAuthenticatedServices AuthenticatedService.asmx Web service we examined earlier. We call the Impersonate method for authenticated users as follows:

    WindowsIdentity identity = null;     WindowsImpersonationContext context = null;     if (Context.User.Identity.IsAuthenticated)     {         identity = Context.User.Identity as WindowsIdentity;         context = identity.Impersonate();     }

The next section of code attempts to read from and write to a file, all of which will take place under the account being impersonated:

    try     {         FileStream fs = new FileStream("C:\\Temp\\Test.txt", FileMode.Open,             FileAccess.Read);         StreamReader reader = new StreamReader(fs);         returnValues[3] = reader.ReadToEnd();         reader.Close();     }     catch     {         returnValues[3] = "Unable to read from file.";     }     try     {         FileStream fs = new FileStream("C:\\Temp\\Test2.txt", FileMode.Create,             FileAccess.Write);         StreamWriter writer = new StreamWriter(fs);         writer.WriteLine("File write access OK.");         writer.Close();         returnValues[4] = "File write access OK.";     }     catch     {         returnValues[4] = "Unable to write to file.";     }

Finally, the code stops impersonating the account by using the Undo method:

    if (Context.User.Identity.IsAuthenticated)     {         context.Undo();     }

Note that this code will use the ASPNET account if no user is authenticated.

Controlling Access to Services

One quick and easy method of authorization is to configure Web services to permit only certain users or groups. You can set up this type of authorization by using the <authorization> element in web.config. This element can contain <allow> and <deny> elements, each of which can specify comma-separated lists of users, roles, and HTTP verbs that can have access to the Web application (using the users, roles, and verbs attributes). For example, the following grants access to the Web application only to users in the Managers role:

<authorization>   <allow roles = "Managers"/>   <deny roles = "*"/> </authorization>
Tip

Users are matched against <allow> and <deny> elements in the order they are listed.

The * wildcard refers to all users, and the ? wildcard can be used to refer to users that haven’t been authenticated.




Programming Microsoft. NET XML Web Services
Programming MicrosoftВ® .NET XML Web Services (Pro-Developer)
ISBN: 0735619123
EAN: 2147483647
Year: 2005
Pages: 172

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net