Pro ASP.NET 2.0 In CSharp 2005 (2005) [eng]
.pdf
748 C H A P T E R 2 1 ■ M E M B E R S H I P
The UpdateUser method just accepts the modified MembershipUser you want to update. Before the method is called, you have to update the properties on your instance. This has just one exception: the IsLockedOut property cannot be set. This property gets automatically set if the user has too many failed login attempts. If you want to unlock a user, you have to call the MembershipUser’s UnlockUser method separately. Similar rules apply to the password. You cannot change the password directly by setting some properties on the MembershipUser. Furthermore, the MembershipUser class has no property for directly accessing the password at all. For this purpose, it supports a GetPassword method and a ChangePassword method that requires you to pass in the old and the new password. Retrieving the password through the GetPassword method is possible, but only if the password is not hashed in the underlying store. Therefore, GetPassword works only if the Membership provider is configured to store the password either in clear text or encrypted in the underlying Membership store.
Creating and Deleting Users
Creating users is as simple as using the rest of the Membership API. You can create users by just calling the CreateUser method of the Membership class. Therefore, if you want to add the feature of creating users to your website, you can add a new page containing the necessary text boxes for entering the required information, then add a button, and finally catch the Click event of this button with the following code:
protected void ActionAddUser_Click(object sender, EventArgs e)
{
try
{
MembershipCreateStatus Status;
Membership.CreateUser(UserNameText.Text,
PasswordText.Text,
UserEmailText.Text,
PwdQuestionText.Text, PwdAnswerText.Text, true, out Status);
StatusLabel.Text = "User created successfully!";
}
catch(Exception ex)
{
Debug.WriteLine("Exception: " + ex.Message); StatusLabel.Text = "Unable to create user!";
}
}
The CreateUser exists with several overloads. The easiest overload just accepts a user name and a password, while the more complex versions require a password question and answer as well. The MembershipCreateStatus object returns additional information about the creation status of the user and is added as an output parameter because the method already returns a new instance of MembershipUser. Depending on the provider’s configuration, your call to simpler versions of CreateUser will succeed or fail. For example, the default Membership provider requires you to include a password question and answer; therefore, if you don’t provide them, a call to CreateUser will result in an exception.
Deleting users is as simple as creating users. The Membership class offers a Delete method that requires you to pass the user name as a parameter. It deletes the user as well as all related information, if you want, from the underlying Membership store.
C H A P T E R 2 1 ■ M E M B E R S H I P |
749 |
Validating Users
Last but not least, the Membership class provides a method for validating a Membership user. If a user has entered his user name and password in a login mask, you can use this method for programmatically validating the information entered by the user, as follows:
if (Membership.ValidateUser(UserNameText.Text, PasswordText.Text))
{
FormsAuthentication.RedirectFromLoginPage(UserNameText.Text, false);
}
else
{
// Invalid username or password
}
Summary
In this chapter, you learned about the Membership API, which is new in ASP.NET 2.0. The Membership API provides you with a full-fledged infrastructure for managing users of your application. You can use either the WAT, the new security controls, or the Membership API for accessing these base services. Membership itself is provider based. In other words, you can exchange the underlying store by changing the underlying provider without touching your application. In this chapter you used only SQL Server as a provider. In Chapter 26 you will learn the necessary details for creating and configuring a custom Membership provider. In the next chapter, you’ll look at a different approach of validating user identity—Windows authentication.
C H A P T E R 2 2
■ ■ ■
Windows Authentication
Forms authentication is a great approach if you want to roll your own authentication system using a back-end database and a custom login page. But what if you are creating a web application for a smaller set of known users who already have Windows user accounts? In these situations, it makes sense to use an authentication system that can leverage the existing user and group membership information.
The solution is Windows authentication, which matches web users to Windows user accounts that are defined on the local computer or another domain on the network. In this chapter, you’ll learn how to use Windows authentication in your web applications. You’ll also learn how to apply impersonation to temporarily assume another identity.
Introducing Windows Authentication
Unlike forms authentication, Windows authentication isn’t built into ASP.NET. Instead, Windows authentication hands over responsibility of authentication to IIS. IIS asks the browser to authenticate itself by providing credentials that map to a Windows user account. If the user is successfully authenticated, IIS allows the web-page request and passes the user and role information onto ASP.NET so that your code can act on it in much the same way that it works with identity information in a forms authentication scenario.
Figure 22-1 shows the end-to-end flow.
Why Use Windows Authentication?
You would want to use Windows authentication for three main reasons:
• It involves little programming work on the developer’s part. |
|
• It allows you to use existing user logins. |
|
• It allows you to use impersonation and Windows security. |
|
The first reason is quite simple—using Windows authentication allows IIS and the client |
|
browser to take care of the authentication process so you don’t need to create a login page, check a |
|
database, or write any custom code. Similarly, Windows already supports basic user account fea- |
|
tures such as password expiry, account lockout, and group membership. |
|
The second, and most important, reason for using Windows authentication is that it allows you |
|
to leverage existing Windows accounts. Typically, you use Windows authentication for applications |
|
where the users are part of the same local network or intranet as your web server. That means you |
|
can authenticate users with the same credentials they use to log into their computers. Best of all, |
|
depending on the settings you use and the network architecture, you may be able to provide |
|
“invisible” authentication that works without forcing a separate login step. Instead, the browser |
751 |
simply uses the logged-in identity of the current user. |
752 |
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-1. The Windows authentication process
The third reason you might want to use Windows authentication is that it allows you to take advantage of existing Windows security settings. For example, you can control access to files by setting Windows file-access permissions. However, it’s important to remember that these permissions don’t take effect automatically. That’s because by default your web application runs using a fixed account (typically ASPNET, as defined in the machine.config file). You can change this behavior by carefully using Windows authentication and impersonation, as described in the “Impersonation and Delegation on Windows Server 2003” section of this chapter.
Why Would You Not Use Windows Authentication?
So, why would you not want to use Windows authentication?
•It’s tied to Windows users.
•It’s tied to Windows client machines.
•It doesn’t provide much flexibility or control and can’t be customized easily.
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 |
753 |
The first problem is that Windows authentication won’t work unless the users you are authenticating already have valid Windows accounts. In a public website, this probably isn’t the case. Even if you could create a Windows account for each visitor, it wouldn’t be as efficient as a database approach for large numbers of users. It also has a potential security risk, because Windows user accounts can have permissions to the web server computer or other network computers. You might not want to risk granting these abilities to your website users.
The second problem is that some of the authentication methods that IIS uses require users to have compatible software on their computers. This limits your ability to use Windows authentication for users who are using non-Microsoft operating systems or for users who aren’t using Internet Explorer.
The final main problem is that Windows authentication doesn’t give you any control over the authentication process. Also, you have no easy way to add, remove, and manage Windows account information programmatically or to store other user-specific information with the user credentials. As you learned in the previous chapter, all these features are easy to add to forms authentication, but they don’t play any part in Windows authentication.
Mechanisms for Windows Authentication
When you implement Windows authentication, IIS uses one of three possible authentication strategies to authenticate each request it receives:
•Basic authentication: The user name and password are passed as clear text. This is the only form of authentication supported by all browsers as part of the HTML standard.
•Digest authentication: The user name and password are not transmitted. Instead, a cryptographically secure hash with this information is sent.
•Integrated Windows authentication: The user name and password are not transmitted. Instead, the identity of a user already logged into Windows is passed automatically as a token. This is the only form of authentication that takes place transparently (without user intervention).
The following sections discuss these options.
■Note There are other less commonly used protocols for Windows authentication. One example is certificatebased authentication. If you use this approach, you must distribute a digital certificate to each client and map each certificate to the appropriate Windows account. Unfortunately, this technique is rife with administrative and deployment headaches. Additionally, IIS 6 supports Advanced Digest authentication (which works essentially the same way as Digest authentication but stores the passwords more securely) and Passport authentication, which allows a user to log in using a Passport account that maps to a Windows user account.
Basic Authentication
The most widely supported authentication protocol is Basic authentication. Almost all web browsers support it. When a website requests client authentication using Basic authentication, the web browser displays a login dialog box for user and password, like the one shown in Figure 22-2.
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 attempts to authenticate the user with the corresponding Windows account.
754 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-2. A login dialog box for Basic authentication
The key limitation of Basic authentication is that it isn’t secure—at least not on its own. User name and password credentials obtained via Basic authentication are transmitted between the client and server as clear text. The data itself is encoded (not encrypted) into a Base64 string that eavesdroppers can easily read. For this reason, you should use Basic authentication only in situations where there’s no need to protect user credentials or only in conjunction with an HTTP wire encryption protocol such as SSL. This way, the data that would otherwise be clearly visible to any network sniffing utility will be encrypted using complex algorithms. (You can find more information on SSL in Chapter 18.)
Digest Authentication
Digest authentication, like Basic authentication, requires the user to provide account information using a login dialog box that is displayed by the browser. Unlike Basic authentication, however, Digest authentication passes a hash of the password, rather than the password itself. (Digest is another name for hash, which explains the name of this authentication scheme.) Because a hash is used, the password itself is never sent across the network, thereby preventing it from being stolen even if you aren’t using SSL.
The process of authenticating a user with Digest authentication works like this:
1.The unauthenticated client requests a restricted web page.
2.The server responds with an HTTP 401 response. This response includes a nonce value—a randomly generated series of bytes. The web server ensures that each nonce value is unique before it issues it.
3.The client uses the nonce, the password, the user name, and some other values to create a hash. This hash value, known as the digest, is sent back to the server along with the plaintext user name.
4.The server uses the nonce value, its stored password for the user name, and the other values to create a hash. It then compares this hash to the one provided by the client. If they match, then the authentication succeeds.
Since the nonce value changes with each authentication request, the digest is not very useful to an attacker. The original password cannot be extracted from it. Similarly, because it incorporates a random nonce, the digest cannot be used for replay attacks, in which an attacker attempts to gain access at a later time by resending a previously intercepted digest.
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 |
755 |
In theory, Digest authentication is a standard, and web servers and web browsers should all be able to use Digest authentication to exchange authentication information. Unfortunately, Microsoft interpreted a part of the Digest authentication specification in a slightly different way than other organizations, such as the Apache Foundation (which provides the Apache web server) and the Mozilla project (which provides the Mozilla web browser). Currently, IIS Digest authentication works only with Internet Explorer 5.0 and later.
Another limitation of Digest authentication in IIS is that it will function only when the virtual directory being authenticated is running on or controlled by a Windows Active Directory domain controller.
Integrated Windows Authentication
Integrated Windows authentication is the most convenient authentication standard for WAN-based/ LAN-based intranet applications, because it performs authentication without requiring any client interaction. When IIS asks the client to authenticate itself, the browser sends a token that represents the Windows user account of the current user. If the web server fails to authenticate the user with this information, a login dialog box is shown where the user can enter a different user name and password.
For integrated Windows authentication to work, both the client and the web server must be on the same local network or intranet. That’s because integrated Windows authentication doesn’t actually transmit the user name and password information. Instead, it coordinates with the domain server or Active Directory instance where it is logged in and gets that computer to send the authentication information to the web server.
The protocol used for transmitting authentication information is either NTLM (NT LAN Manager) authentication or Kerberos 5—depending on the operating system version of the client and the server. If both are running Windows 2000 or higher and both machines are running in an Active Directory domain, Kerberos is used as the authentication protocol; otherwise, NTLM authentication will be used. Both protocols are extremely secure (Kerberos is the most secure protocol currently available), but they are limited. Therefore, in general, integrated authentication works only on Internet Explorer 2.0 or higher (integrated Windows authentication is not supported in non–Internet Explorer clients). Kerberos, of course, works only for machines running Windows 2000 or higher, and neither protocol can work across a proxy server. In addition, Kerberos requires some additional ports to be open on firewalls. In the following section, you will learn the basics of the authentication protocols used for integrated Windows authentication. These concepts will help you understand the configuration steps, especially for impersonation and delegation.
NT LAN Manager Authentication
NTLM authentication is integrated into the Windows operating system since it has built-in network support. NTLM authenticates clients through a challenge/response mechanism that is based on a three-way handshake between the client and the server. Everything you will learn about in this section takes place on the operating system automatically. Of course, this works only if the client and the server are running Windows.
Basically, the client starts the communication by sending a message to the server, which indicates that the client wants to talk to the server. The server generates a 64-bit random value called the nonce. The server responds to the client’s request by returning this nonce. This response is called the challenge. Now the client operating system asks the user for a user name and password. Immediately after the user has entered this information, the system hashes the password. This password hash—called the master key—will then be used for encrypting the nonce. Together with the user name, the client transmits the encrypted nonce in his response to the server (completing the challenge/response mechanism).
756 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
The server now needs to validate the returned nonce. Depending on whether the user is a local user or a domain user, this validation takes place locally or remotely on the domain controller. In both cases, the user’s master key, which is the hashed version of the password, is retrieved from the security account database. This master key then encrypts the clear-text nonce again on the server (of course, the server has cached the clear-text nonce before it transmits the data to the client). If the re-created encrypted version of the nonce matches the encrypted version returned from the client, the user is authenticated successfully, and a logon session is created on the server for the user. Figure 22-3 shows the process flow.
Figure 22-3. The NTLM protocol at a glance
As you can see, the password is never transmitted across the wire. Even the hashed version of the password is never transmitted. This makes NTLM really secure. But there is even a more secure protocol with additional possibilities, as you will see in the next section.
Kerberos Authentication: A Short Introduction
Currently, Kerberos 5 is the most secure authentication protocol available. It is a well-known public standard created by the IETF (Internet Engineering Task Force), and it implements a ticket-based authentication protocol. On Windows operating systems, Kerberos has been available since Windows 2000. When activating integrated Windows authentication, Windows will use Kerberos automatically under the following circumstances:
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 |
757 |
•The client and the server are running Windows 2000 or higher.
•An Active Directory Domain with a primary domain controller (which automatically plays the role of the so-called key distribution center) is available in the network.
In any other case, Windows will select NTLM as the authentication protocol. Although covering Kerberos in detail requires a book of its own, you will learn about the basic concepts in this chapter. These concepts will help you understand the necessary configuration tasks and when each feature will work. For example, one of the big differences between NTLM and Kerberos is that Kerberos supports both impersonation and delegation, while NTLM supports impersonation only.
Delegation basically is based on the same concept as impersonation. It involves merely performing actions on behalf of the client’s identity. But while impersonation just works within the scope of one machine, delegation works across the network as well. This means the authentication ticket of the original client’s identity can be passed to another server in the network if the originally accessed server machine has the permission to do so. You will learn more about impersonation and delegation later in the “Impersonation” section. For now it’s important to understand that Kerberos supports both impersonation and delegation, while NTLM and other Windows authentication techniques such as Basic or Digest authentication support impersonation only.
The core component of a Kerberos system is the KDC (key distribution center), which is responsible for issuing tickets and managing credentials. In the Windows world, an Active Directory primary domain controller plays the role of the KDC. Every actor, client, and server has to trust the KDC. It manages all the user and computer accounts and issues authentication tickets and session tickets for communication sessions between machines in the domain. This is another big difference when comparing Kerberos to NTLM: while NTLM works for workgroup scenarios without a central authority, Kerberos requires a central authority for issuing any type of ticket. Therefore, for Kerberos to work, you require a connection to an Active Directory domain controller. Figure 22-4 shows the flow for authenticating a user and then establishing a session between the client and the simple member server of a domain.
Every user authentication process starts with submitting a request to the authentication service, which runs on the KDC. This request contains the user name of the user to be authenticated. The KDC reads the user’s master key from the security account database. Again, this is the hashed version of the user’s password. Afterward, it creates a TGT (ticket-granting ticket). This ticket contains a session key for the user’s session as well as an expiration date and time. Before the ticket is returned to the client, the server encrypts it using the user’s master key. With only the correct password entered on the client, the client operating system can create the correct the master key (the hash) for successfully decrypting the TGT received from the server. If decryption of the TGT succeeds on the client, the user is authenticated successfully. Finally, the client caches the TGT locally.
When the client wants to communicate with another member server in the network, it first has to ask the KDC for a session ticket. For this purpose, it sends the locally cached TGT to a so-called ticket-granting service that runs on the KDC. This service validates the TGT, and if it’s still valid (not expired, not tampered with, and so on), it generates a session key for the communication session between the client and the member server. This session key is then encrypted with the client’s master key. In addition, the session key is packaged into an ST (session ticket), which contains additional expiration information for the server. This session ticket is encrypted with the member server’s master key. Both the encrypted session key and the encrypted session ticket are forwarded to the client. The client decrypts the session key and forwards the session ticket to the server. Of course, both the server and the client are well known to the KDC, as somewhere in the past both have been joined to the domain (joining a machine to a domain means establishing a trust relationship between this machine and the KDC). Therefore, the KDC knows the client’s and the member server’s master keys.
