Forms Authentication In Asp.Net 2.0 3.5

2:05:00 am 0 Comments

Forms Authentication in ASP.NET 2.0 is technique to decide how users can access your web application.
Using froms authentication we can decide certain users can access only certain pages or we can control the anonymous access, we can implement folder level access and access based on roles

we can manage the access through web.config file

Read my article on implementing forms authentication using FormsAuthentication ticket and managing roles

1. First of all create a new website and add a new form , name it Login.aspx
Drag login control on it from the toolbox
Make sure you have a web.config file in root of your application

2. Right click on solution explorer and add new folder , name it membersArea
Add a new from and name it members.aspx
Add a web.config file in this folder.

Now to implement Forms Authentication we need to configure web.config file (in the application root)

For this we need to add Authentication and Authorization tags inside <system.web> tag of web.config

<system.web>
<authentication mode="Forms">
<forms defaultUrl="Default.aspx" loginUrl="~/Login.aspx"
slidingExpiration="true" timeout="20">
</forms>
</authentication>
</system.web>

Now To restrict access to the membersonly page which is inside membersonly folder so that only members can access this page we need to create a another web.config file inside this folder to provide it's access rules
In this web.config write this inside <system.web> tag
<system.web>
<authorization>
<deny users="?"/>
</authorization>
</system.web>

Now for login process and checking the username and password we need to write this code, double click on the login control placed on the Login.aspx page, it will generate Login1_Authenticate event
protected void Login1_Authenticate
(object sender, AuthenticateEventArgs e)
{
bool isMember = AuthenticateUser(Login1.UserName, Login1.Password,
Login1.RememberMeSet);

if (isMember)
{
FormsAuthentication.RedirectFromLoginPage(Login1.UserName,
Login1.RememberMeSet);
}
}

And this for checking username and password, i m using hard coded values
private bool AuthenticateUser(string userName, string password, bool rememberUserName)
{
string userName = "amiT";
string password = "password";

if (userName.Equals(userName) && password.Equals(password))
{
return true;
}
else
{
return false;
}
}

0 comments: