Determining Windows Users for Web Forms Applications

In this example we will see how to determine the identity of the logged in user for an ASP.Net Web Forms using Windows Authentication.

In this example we will see how to determine the identity of the logged in user for an ASP.Net Web Forms using Windows Authentication. 

Step 1: Setting up the Folder Security

In Windows Explorer, navigate to the folder that is to be setup for the security. Right click on the folder and click on the Properties option. Click on the Security Tab now. Unselect the option "Allow inheritable permissions from Parent to propagate to this object. Click on the Remove button to deselect all the permissions inherited from the parent folder.

Click on the Add button and add the Windows users and Groups that should be granted permission.

UsersF1.gif

Figure : Add the Windows Users/ Groups that need to be granted permission to the web site. 

Step 2: Selecting the Authentication Types

Click on Start->Programs ->Administrative Tools and select "Internet Services Manager" 

Click on the node for "Default Web Site" and create a new Virtual Directory "SecurityTest" pointing to the folder that contains our web application files. 

Right click on the virtual Directory "SecurityTest" and click on "Properties". Click on the "Directory Security" tab.

UsersF2.gif

Figure: SecurityTest properties in Internet Services Manager

Click on the Edit button under "Anonymous access and authentication control"

UsersF3.gif

Figure: Select the Authentication Method 

Clear the checkbox for "Anonymous Access" and make sure the "Integrated Windows Authentication" check box is selected. 

Click on OK and exit from the Internet Services Manager. 

Step 3: Identify the logged-in user. 

Use the following code to get the identity of the logged on user: 

WindowsPrincipal wp = new WindowsPrincipal(WindowsIdentity.GetCurrent());"
Label1.Text = wp.Identity.Name; 

In this example we display the user's identity in a label on an ASP.Net page. You can process this information further, to grant/deny permissions or display personalized content to the user.

Don't forget to include a reference to the System.Security.Principal namespace in the code. 

The complete code listing is mentioned below. 

<%@ Page Language="C#" %>
<%@ Import Namespace="System" %>
<%@ Import Namespace="System.Security.Principal" %>

<script language="C#" runat="server" >
private void Button1_Click(object sender, System.EventArgs e)
{
WindowsPrincipal wp = new WindowsPrincipal(WindowsIdentity.GetCurrent());
Label1.Text = wp.Identity.Name;
}
</script>
<
html>
<
head><title> Windows User</title></head>
<
body>
<
form runat="server" ID="Form1">
<
asp:Button id="Button1" runat="server" Text="Display User" OnClick="Button1_Click"></asp:Button>
<
asp:Label id="Label1" runat="server" Width="234px">Label</asp:Label>
</
form>
</
body>
</
html>

Code Listing : Display User's Identity

UsersF4.gif

Figure 4: Example usage