Windows Authentication in Asp.Net Web Application

When we are building any intranet web application, it is always better go with windows authentication in order to authenticate user against AD(Active Directory). With windows authentication enabled its very easy to authenticate and authorize user.

To enable Windows Authentication in Asp.Net web application below changes need to be done:

Set authentication mode to “Windows” and impersonate to “True” in web.config file under <system.web> node

Or the same can be done in IIS. For that, select web application from the list and for the selected application in right panel select “Authentication” option.

Under “Authentication” enable “Impersonation” and “Windows Authentication”

Once, windows authentication is enabled then we need to use it in code for authentication and authorization purpose.

For Authentication:

//Obtain the authenticated user's Windows token.

IIdentity WinId = HttpContext.Current.User.Identity;

//To get LoggedIn user details

WindowsIdentity identity = HttpContext.Current.Request.LogonUserIdentity;

//Sets Machine logged-in username to private variable

_userName = identity.Name;

//Returns "True" if user is validated against AD else returns "False".
                return identity.IsAuthenticated;

For Authorization:

//Can perform role-based authorization in code either by performing explicit role checks (User.IsInRole or Roles.IsUserInRole), or by using PrincipalPermission demands.

//Ways to perform role based authorization

User.IsInRole(@"DomainName\Manager");
Roles.IsUserInRole(@"DomainName\Manager");

var user = (WindowsPrincipal)User;
if (user.IsInRole(WindowsBuiltInRole.Administrator))
{
    //user is an administrator
}

Windows provides set of built-in roles for authorization

Complete Implementation:

Hope this helps.

Thanks!!

This article is part of the GWB Archives. Original Author: Manjunath K

New on Geeks with Blogs

  • We Won The One Award I Actually Care About

    Full Scale made the Inc. 5000 for the fifth year straight, the 12th listing across my three companies. Here is why the one award you cannot buy is worth stopping for.

  • Your Customers Build the Features Now

    I let a tool I liked sit dead for a year rather than build the features I wanted. An MCP server meant I never had to, and your customers can do the same to your product.

  • Get the Size of a Directory in Linux the Easy Way

    du -sh for the quick answer, ncdu for the cleanup, df for the disk itself: every command for checking directory size in Linux, plus why du and df never agree.

  • Vim Search and Replace: The Ultimate Guide

    One :%s command replaces every match in a file before a find dialog would even open. The Vim substitute patterns worth the muscle memory: flags, ranges, capture groups, and multi-file edits.