9.4. 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 ...

Get ASP.NET 2.0 Cookbook, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.