Sunday, February 7, 2010

ASP.NET SECURITY: AUTHENTICATION AND AUTHORIZATION

ASP.NET gives developers very flexible and powerful capabilities in to secure to make decisions considering user actions.To apply settings we want, we can edit web.config, machine.config, IIS.Besides this settings there are great classes and namespaces in .NET ( we will use generally system.web.security ).Let's start with element in web.config. (Authentication is the process that determines the identity of a user, in other words asking user his/her credentials.Authorization,on the other hand, after validating credential, giving the user access to any specific part of the application)

>authentication mode="Forms"> //possible values are "Windows|Forms|Passport|Name

>/authentication>
90% we use authentication mode "Forms" so no need to focus on other types.By using >authorization> we define accession rules for specific folders or pages or website as a whole.

>authorization>

>deny users="*"/>

>allow roles="administrator"/>

>/authorization>

This setting first of all denies all users (*) then gives the access right to the role administrator.If we place this xml in web.config on the root of the application then it uses these settings for whole website.But in specific folders it is applied only to that folder. ie in our example, it seems that this code is for admin directory ( it gives access rights just for administrator(s).) We have deny and allow tags and users and roles attributes.For our need we can use them appropriate combination.And an example of how to use system.web.security and its basic functionalities:

using System.Web.Security;
protected void LoginButton_Click(object sender, EventArgs e)
{
if (Membership.ValidateUser(TextBox1.Text, TextBox2.Text)) //this method takes two arguments username,password
{
FormsAuthentication.RedirectFromLoginPage(TextBox1.Text, true); //go to page which was intended
//before redirected to loginpage
}
else
FormsAuthentication.RedirectToLoginPage(); //otherwise go to loginpage again
}
}