Saturday, July 27, 2013

Windows Authentication using ASP .Net in detail


Authentication



Authentication is the process of obtaining identification credentials such as name and password from a user and validating those credentials against some authority. If the credentials are valid, the entity that submitted the credentials is considered an authenticated identity.

In windows authentication users are authenticated against the users available in Windows operating system (local) or against that of users available in Active Directory.

For windows authentication we need to set the authentication mode to windows in web.config.
 


Now to impersonate the identity of IIS worker process to that of provided by Windows operating system
We will have to set the impersonate to True by adding <identity impersonate="true" />

So the final code will look like this





Now the question is how do I determine whether I am truly authenticated?  Basically I can twist my question into other way “How to get my username in Windows Authentication?” Well that’s pretty much simple I guess.

Well for that we will have to use System.Security.Principal namespace.
The code for getting complete username along with domain name as well as for getting only username/ userId is shown below:
  

C# Code:





VB Code:





So far we have seen how to get username/userid now the question is how to determine whether the user is authenticated?

Well for that there is a simple property IsAuthenticated in GetCurrent() of WindowsIdentity class.
A sample code for that is as below:



C# Code:





VB Code:





So far as I am concerned about authenticating a user things are fine Now what if I want to check whether it really works for some other user?

Ok for that case just go to Control Panel\User Accounts\User Accounts and inside that click on Manage User Accounts and click on add for adding a user.

  1. Say for if you want a add a user ‘durandose’.
  2. Then Go to Control Panel\User Accounts\User Accounts (In Windows 7 Professional)
  3. Now click on Add and now simply add a user ‘durandose’ select a domain if you want to add that person to a specific domain.
  4. Once you are done just click on ‘Next’ and select the roll etc.
  5. Now try login through that user and access that site, you should be able to get access to that page if everything has been done as per above instruction.
 Ok! If this was Windows Authentication!?! Then What would be Form Authentication, Passport Authentication and LDAP Authentication?!?! :D

Stay tuned for upcoming post!