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!!
