Recipe 8.4 Using Windows Authentication

     

8.4.1 Problem

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

8.4.2 Solution

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

Make the following 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>  

In the code-behind class for the ASP.NET page, get the current user's identity and check the user 's roles using the identity property from the current context:

 
figs/vbicon.gif
 identity = CType(Context.User.Identity, WindowsIdentity) 
figs/csharpicon.gif
 identity = (WindowsIdentity)(Context.User.Identity); 

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

Figure 8-2. Windows authentication dialog box
figs/ancb_0802.gif

Figure 8-3. Windows authentication sample page
figs/ancb_0803.gif

8.4.3 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 already 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 having to maintain all this information separately in your application.

The setup required for using Windows authentication is very 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 8.1 for more on Forms authentication.)

For Windows authentication, IIS must be configured to block anonymous access and must be configured to use either 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, and 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 setting 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. There are two negatives to doing this, however. 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 name is "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 8.2, you can also place pages with the same access requirements in folders and include a <location> element defining the access to the folders. See Recipe 8.2 and Recipe 8.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:

 
figs/vbicon.gif
 identity = CType(Context.User.Identity, WindowsIdentity) 
figs/csharpicon.gif
 identity = (WindowsIdentity)(Context.User.Identity); 

When using 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; she is likely to know all the fine points.


8.4.4 See Also

Recipe 8.1; Recipe 8.2; Recipe 8.3; MSDN documentation for IIS setup (search for "IIS authentication")

Example 8-11. web.config for Windows authentication
 <?xml version="1.0" encoding="utf-8" ?> <configuration> <system.web> ..  <authentication mode="Windows" />   <identity impersonate="true" />   <authorization>   <deny users="*" /> <!-- Deny all users -->   </authorization>  .. <!-- **************************************************************************** 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 8-12. Windows authentication sample page (.aspx)
 <%@ Page Language="vb" AutoEventWireup="false" Codebehind="DisplayUserInformation.aspx.vb" Inherits="ASPNetCookbook.VBSecurity84.DisplayUserInformation" %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> <html> <head> <title>DisplayUserInformation</title> <link rel="stylesheet" href="css/ASPNetCookbook.css"> </head> <body leftmargin="0" marginheight="0" marginwidth="0" topmargin="0"> <form id="frmSecurity" method="post" runat="server"> <table width="100%" cellpadding ="0" cellspacing="0" border="0"> <tr> <td align="center"> <img src="images/ASPNETCookbookHeading_blue.gif"> </td> </tr> <tr> <td class="dividerLine"> <img src="images/spacer.gif" height="6" border="0"></td> </tr> </table> <table width="90%" align="center" border="0"> <tr> <td><img src="images/spacer.gif" height="10" border="0"></td> </tr> <tr> <td align="center" class="PageHeading"> Using Windows Authentication (VB) </td> </tr> <tr> <td><img src="images/spacer.gif" height="10" border="0"></td> </tr> <tr> <td align="center"> <table> <tr> <td class="LabelText">User Name: </td> <td> <asp:Label ID="txtUserName" Runat="server" CssClass="LabelText" /> </td> </tr> <tr> <td class="LabelText">Authentication Type: </td> <td> <asp:Label ID="txtAuthenticationType" Runat="server" CssClass="LabelText" /> </td> </tr> <tr> <td class="LabelText">Is In Administrators Group: </td> <td> <asp:Label ID="txtAdminGroup" Runat="server" CssClass="LabelText" /> </td> </tr> <tr> <td class="LabelText">Is In Users Group: </td> <td> <asp:Label ID="txtUsersGroup" Runat ="server" CssClass="LabelText" /> </td> </tr> </table> </td> </tr> </table> </form> </body> </html> 

Example 8-13. Windows authentication sample page code-behind (.vb)
 Option Explicit On Option Strict On '----------------------------------------------------------------------------- ' ' Module Name: DisplayUserInformation.aspx.vb ' ' Description: This module provides the code behind for the ' DisplayUserInformation.aspx page ' '***************************************************************************** Imports System.Security.Principal Namespace ASPNetCookbook.VBSecurity84 Public Class DisplayUserInformation Inherits System.Web.UI.Page 'controls on the form Protected txtUserName As System.Web.UI.WebControls.Label Protected txtAuthenticationType As System.Web.UI.WebControls.Label Protected txtAdminGroup As System.Web.UI.WebControls.Label Protected txtUsersGroup As System.Web.UI.WebControls.Label '************************************************************************* ' ' ROUTINE: Page_Load ' ' DESCRIPTION: This routine provides the event handler for the page load ' event. It is responsible for initializing the controls ' on the page. '------------------------------------------------------------------------- Private Sub Page_Load(ByVal sender As System.Object, _ ByVal e As System.EventArgs) _ Handles MyBase.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 8-14. Windows authentication sample page code-behind (.cs)
 //---------------------------------------------------------------------------- // // Module Name: DisplayUserInformation.aspx.cs // // Description: This module provides the code behind for the // DisplayUserInformation.aspx page // //**************************************************************************** using System; using System.Security.Principal; namespace ASPNetCookbook.CSSecurity84 { public class DisplayUserInformation : System.Web.UI.Page { // controls on the form protected System.Web.UI.WebControls.Label txtUserName ; protected System.Web.UI.WebControls.Label txtAuthenticationType; protected System.Web.UI.WebControls.Label txtAdminGroup; protected System.Web.UI.WebControls.Label txtUsersGroup ; //************************************************************************ // // ROUTINE: Page_Load // // DESCRIPTION: This routine provides the event handler for the page // load event. It is responsible for initializing the // controls on the page. //------------------------------------------------------------------------ private void Page_Load(object sender, System.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: 2006
Pages: 179

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