Recipe 9.5. Using Windows Authentication


Problem

You want to use existing Windows network accounts for authenticating users of your application.

Solution

Configure IIS to block anonymous access and to require Windows integrated authentication.

Make the following four changes to web.config:

  1. Specify Windows authentication:

     <authentication mode="Windows" /> 

  2. Set the <identity> element to impersonate:

     <identity impersonate="true" userName="" password="" /> 

  3. Configure the <authorization> element to deny access to all users:

     <authorization> <deny users="*" /> <!-- Deny all users --> </authorization> 

  4. Add a <location> element for each page to which you want to control access with an <allow> child element and attribute (to allow access to the page by certain roles) followed by a <deny> child element and attribute (to deny access to all users not listed in the previous roles):

     <location path="DisplayUserInformation.aspx">   <system.web>     <authorization>   <allow roles="BuiltIn\Users,    BuiltIn\Administrators"/>   <deny users="*"/> </authorization>   </system.web> </location> 

The code we've implemented to illustrate this solution appears in Examples 9-11, 9-12, 9-13 through 9-14. Example 9-11 shows the Windows authentication and role settings in web.config for the sample ASP.NET page. Example 9-12 shows the Windows authentication sample .aspx file. The code-behind class for the page appears in Examples 9-13 (VB) and 9-14 (C#). Figure 9-2 shows the Windows authentication dialog box, and Figure 9-3 shows a sample page produced by the application.

Figure 9-2. Windows authentication dialog box


Figure 9-3. Windows authentication sample page


Discussion

Windows authentication is a useful means of authenticating users of web applications that run on an intranet. Windows authentication allows you to assume that each user has a valid Windows account with appropriate permissions for accessing the network resources. This is an advantage to you as a web application developer because it saves you from having to maintain all this information separately in your application.

The setup required for using Windows authentication is similar to the setup performed for Forms authentication. The big difference is the role IIS plays in the authentication. To support Forms authentication, IIS is configured to allow anonymous access. In other words, IIS does not perform any authentication, leaving the task of authenticating and authorizing users to ASP.NET. (See Recipe 9.1 for more on Forms authentication.)

For Windows authentication, IIS must be configured to block anonymous access and must be configured to use Windows integrated authentication or basic authentication. We recommend Windows integrated authentication because this method does not send the user password over the network in clear text. With Windows authentication, IIS verifies that the user is allowed to access the application; then ASP.NET performs the authorization for the requested resource. The operating system can also be involved in the authorization by using Access Control Lists (ACLs) to limit access to resources by specific users.

After you set up IIS, the web.config file should be set up with the authentication mode set to Windows:

 <authentication mode="Windows" /> 

The <identity> element should be set to impersonate:

 <identity impersonate="true" userName="" password="" /> 

This configures ASP.NET to impersonate the user authenticated by IIS for all resource requests when the userName and password are empty strings. If you want all requests to use a different account than IIS used for authentication, the userName and password attributes of the <identity> element can be set to the desired username and password. However, there are two negatives if you do this. First, the password for the account is in clear text in web.config, which can cause security risks. Second, logging and auditing cannot be done on a per-user basis.

The <authorization> section is configured to deny access to all users:

 <authorization> <deny users="*" /> <! Deny all users > </authorization> 

This is done because <location> elements will be added to define the authorizations for each page.

To control the access to each page, add a <location> element. This provides the maximum flexibility in controlling access to each page in your application. When using Windows authentication, roles are synonymous with groups. Therefore, the <allow> element should contain the list of groups (roles) allowed to access the given page. The <deny users="*"/> element should always be provided after the <allow> element to deny access to all users not listed in the previous roles. For example:

 <location path="DisplayUserInformation.aspx">   <system.web> <authorization>   <allow roles="BuiltIn\Users,   BuiltIn\Administrators"/>   <deny users="*"/> </authorization>   </system.web> </location> 

Group (role) names must be fully qualified. When using local built-in groups such as Users and Administrators, the fully qualified names are BuiltIn\Users and BuiltIn\Administrators. When using groups you have created, you must include the computer name, such as <MyComputer> \Testers. When using domain groups, you must include the domain name, such as <DomainName>\Testers.


As described in Recipe 9.2, you can place pages with the same access requirements in folders and include a <location> element defining the access to the folders. See Recipes 9.2 and 9.3 for more information on using folders in this way, including a discussion of the pros and cons of various folder-related approaches.

No other code is required in your application to implement Windows authentication.

You can access the user credentials in your application by using the identity property from the current context. Because Windows authentication is being used and more information is available for the user than is available using Forms authentication, the identity property should be cast as a WindowsIdentity type to access these additional properties:

 

identity = CType(Context.User.Identity, WindowsIdentity)

identity = (WindowsIdentity)(Context.User.Identity);

Windows authentication, the client browser, IIS, and Windows perform many functions behind the scenes. If you access the application from the same machine or from a machine in the same domain, you may not be prompted to enter your username and password. This is caused by the browser automatically sending your credentials when the challenge is issued by IIS. Whether or not this happens is a function of the requested URL, how IIS is configured, and how your browser is configured. The details of this configuration are beyond the scope of this book. If you're interested in this topic, consult your network administrator, who will probably know all the fine points.


See Also

Recipes 9.1, 9.2, and 9.3; MSDN documentation for IIS setup (search for "IIS authentication")

Example 9-11. web.config for Windows authentication

 <?xml version="1.0"?> <configuration> <system.web>   … <authentication mode="Windows" /> <identity impersonate="true" /> <authorization>   <deny users="*" />   <!-- Deny all users --> </authorization>   … </system.web> <!-- **************************************************************************** The following section defines the pages in the application and the roles (groups) that are allowed to access them. Any group defined in Windows can be used. NOTE: The groups must be the fully qualified names such as BuiltIn\Administrators, etc. **************************************************************************** --> <location path="DisplayUserInformation.aspx">   <system.web>     <authorization> <allow roles="BuiltIn\Users,  BuiltIn\Administrators"/> <deny users="*"/>   </authorization> </system.web> </location> </configuration> 

Example 9-12. Windows authentication sample page (.aspx)

 <%@ Page Language="VB" MasterPageFile="~/ASPNetCookbookVB.master" AutoEventWireup="false" CodeFile="DisplayUserInformation.aspx.vb" Inherits="ASPNetCookbook.VBExamples.DisplayUserInformation" Title="Display User Information" %> <asp:Content  runat="server" ContentPlaceHolder> <div align="center" > Using Windows Authentication (VB) </div> <table width="60%" align="center" border="0">   <tr> <td >User Name: </td> <td>   <asp:Label  Runat="server"  Css /> </td>   </tr>   <tr> <td >Authentication Type: </td> <td>   <asp:Label  Runat="server" Css /> </td>   </tr>   <tr> <td >Is In Administrators Group: </td> <td>   <asp:Label  Runat="server" Css /> </td>   </tr>   <tr> <td >Is In Users Group: </td> <td>   <asp:Label  Runat="server" Css /> </td>   </tr> </table> </asp:Content> 

Example 9-13. Windows authentication sample page code-behind (.vb)

 Option Explicit On Option Strict On Imports System.Security.Principal Namespace ASPNetCookbook.VBExamples ''' <summary> ''' This class provides the code behind for ''' DisplayUserInformation.aspx ''' </summary> Partial Class DisplayUserInformation Inherits System.Web.UI.Page '''*********************************************************************** ''' <summary> ''' This routine provides the event handler for the page load event. It ''' is responsible for initializing the controls on the page. ''' </summary> ''' ''' <param name="sender">Set to the sender of the event</param> ''' <param name="e">Set to the event arguments</param> Private Sub Page_Load(ByVal sender As Object, _   ByVal e As System.EventArgs) Handles Me.Load Dim identity As WindowsIdentity 'get the current user's identity identity = CType(Context.User.Identity, WindowsIdentity) 'output the user's name and authentication type txtUserName.Text = identity.Name txtAuthenticationType.Text = identity.AuthenticationType 'check to see if the user is a member of the administators group If (Context.User.IsInRole("BuiltIn\Administrators")) Then txtAdminGroup.Text = "Yes" Else txtAdminGroup.Text = "No" End If 'check to see if the user is a member of the users group If (Context.User.IsInRole("BuiltIn\Users")) Then txtUsersGroup.Text = "Yes" Else txtUsersGroup.Text = "No" End If End Sub 'Page_Load   End Class 'DisplayUserInformation End Namespace 

Example 9-14. Windows authentication sample page code-behind (.cs)

 using System; using System.Security.Principal; namespace ASPNetCookbook.CSExamples { /// <summary> /// This class provides the code behind for /// DisplayUserInformation.aspx /// </summary> public partial class DisplayUserInformation : System.Web.UI.Page {   ///***********************************************************************   /// <summary>   /// This routine provides the event handler for the page load event.   /// It is responsible for initializing the controls on the page.   /// </summary>   ///   /// <param name="sender">Set to the sender of the event</param>   /// <param name="e">Set to the event arguments</param>   protected void Page_Load(object sender, EventArgs e)   { WindowsIdentity identity = null; // get the current user's identity identity = (WindowsIdentity)(Context.User.Identity); // output the user's name and authentication type txtUserName.Text = identity.Name; txtAuthenticationType.Text = identity.AuthenticationType; // check to see if the user is a member of the administators group if (Context.User.IsInRole("BuiltIn\\Administrators")) { txtAdminGroup.Text = "Yes"; } else { txtAdminGroup.Text = "No"; } // check to see if the user is a member of the users group if (Context.User.IsInRole("BuiltIn\\Users")) { txtUsersGroup.Text = "Yes"; } else { txtUsersGroup.Text = "No"; }   } // Page_Load } // DisplayUserInformation } 



ASP. NET Cookbook
ASP.Net 2.0 Cookbook (Cookbooks (OReilly))
ISBN: 0596100647
EAN: 2147483647
Year: 2003
Pages: 202

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