Monday, March 19, 2012

Handling Authentication and Authorization in ASP.NET

Handling authentication and authorization is one of the important things that we should consider when developing a interactive web site. First of all we should identify the difference between authentication and authorization, since these two words gives a total different meanings.

Authentication means verification of the user's identity which also means verifying the user who he claims to be. Once the user has been authenticated, the authorization process determines whether that identity has access to a given resource. For example if the user is an Administrator, he is authorized to do all the changes in all the resources, If he is a normal user, he is only authorized to do some changes, or may be he will not be able to do any changes. So basically Authorization is checking whether the user has relevant rights to access the resources.

So in ASP.NET, we can use three ways to handle authentication and authorization.
  1. Windows Authentication
  2. Forms Authentication
  3. Passport Authentication


01. Windows Authentication

Windows Authentication is mostly used in web sites running in a intranet. This mode of authentication uses standard windows user names and passwords as user's credentials to access the website. This is how you can enable Windows Authentication in you web site. Change your Web.config file as follows.
<authentication mode="Windows">
        
</authentication>
      
<authorization>
    <allow users="RAVANA\Jaliya"/> <!--allow Jaliya to access-->
    <deny users="*"/><!--deny all users except allowed users-->
</authorization>
Now you have all set for your Windows Authentication in the Web.config file. In here under <authorization> there are several things that you can change like allow/deny all/some/none users and roles etc. Then what you have to do is enable Windows Authentication in IIS. For that go to IIS, select your web site and in your right hand panel double click on Authentication. right click on Windows Authentication and click on Enable. Now try to browser your site and you will be presented with a login page.



02. Forms Authentication

Forms Authentication is mostly used in web sites running in internet. Forms authentication lets you authenticate users by using your own code and then maintain an authentication token in a cookie or in the page URL. You can create a login page that collects credentials from the user and that includes code to validate and authenticate the credentials. To validate we need to compare the submitted information with some kind of previously entered information. We can use the Web.config file, a SQL Server database, a customer database, windows active directory and various other kinds of data sources to store those information.

This is how forms authentication handles authentication.
  • We generally configure the application to redirect all the unauthenticated requests to the login page when users try to access a protected web page. User inputs their credentials and after validating them, if they are correct, then we redirect the request back to the originally requested page with an appropriate authentication ticket (cookie). 
  • If you do not want to redirect to be done, you can just get the forms authentication cookie and set it to the user. So since now user have cookie attached, user's browser passes the authentication cookie with the request.  Because of that on subsequent requests, user will be bypassing the login page when he is requested for credentials.
Let's see how to configure forms authentication in a web site. By default when you create a web site in Visual Studio 2010, in Web.config file <authentication mode=" "> is set to "Forms".
<authentication mode="Forms">
    <forms loginUrl="~/Account/Login.aspx" timeout="2880" defaultUrl="Home.aspx" cookieless=""/>
</authentication>
The values you can set here are,
  • loginUrl - URL for the login page that the FormsAuthentication class will redirect to if no valid authentication cookie is found.
  • timeout - Specifies the time, in integer minutes. Sets the authentication time-out.
  • defaultUrl - URL that the FormsAuthentication class will redirect after successfull authentication.
  • cookieless - The default is UseDeviceProfile.
    • AutoDetect - Specifies that cookies are used, if the device profile supports cookies; otherwise, cookies are not used. For desktop browsers that are known to support cookies, a probing mechanism will be used to try to use cookies, when enabled. If a device does not support cookies, no probing mechanism will be used. Simply means depending on your browser configuration it can either use cookies or pass the authentication information encrypted via browser URL.
    • UseCookies -  Specifies that cookies will always be used, regardless of the device and you would like the forms authentication mechanism to create cookie when the authentication is successful.
    • UseDeviceProfile - Specifies that cookies are used, if the browser supports cookies; otherwise, cookies are not used. For devices that support cookies, no attempt is made to probe to determine whether cookie support is enabled.
    • UseUri - Specifies that cookies will never be used. You would like to pass data encrypted via the browser URL query string.
Now in your Login button click event,
using System.Web.Security;

protected void btnLogin_Click(object sender, EventArgs e)
{
    if (ValidateUser(txtUserName.text, txtPassword.text))
    {
        //true to CreatePersistentCookie
        FormsAuthentication.RedirectFromLoginPage(txtUserName.text, true);
    }
    else
    {
        FormsAuthentication.RedirectToLoginPage();
    }
}

private bool ValidateUser(string username, string password)
{
    //your own validation code
    //return true or false
}
There are couple of things you should know. To get a better understanding about the concept here, you can store user names and passwords in Web.config file which is of course not recommended in production environment and validate them by calling Authenticate method in the FormsAuthentication class instead of writing custom validation.
FormsAuthentication.Authenticate(txtUserName.text, txtPassword.text);
Roles

ASP.NET provides the concept of roles that gives each role a different view on specific pages.
<location path="Finance">
    <system.web> 
        <authorization>
            <allow roles="Fin" />
            <deny users="*" />
        </authorization>
    </system.web>
</location>
Location here means the folder name which holds the .aspx for some specific role. In here, <location path="Finance"> means that all .aspx files under the  Finance folder are protected. <allow roles="Fin" /><deny users="*" /> mean deny every one from accessing pages under Finance except those having the Fin role.

Using forms authentication you can implement Single Sign-On(SSO) in which when you successfully logged in to one site, you don't need to enter your credentials to other related sites. You are signed on across multiple sites.


03. Passport Authentication

Passport authentication is based on the passport website provided by the Microsoft. It is a single sign-on web service developed and provided by Microsoft that allows users to log in to many websites using one account. So when user logins with credentials it will be reached to the passport website where authentication will happen. If Authentication is successful it will return a token to your website.

So this post has only described the basics of Authentication and Authorization in ASP.NET. It's up for you to explore the rest. Appreciate your feedback.

Happy Coding.

Regards,
Jaliya