Saturday, March 17, 2012

Forms Authentication In Asp.Net 2.0 3.5

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

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
<authentication mode="Forms">
<forms defaultUrl="Default.aspx" loginUrl="~/Login.aspx"
slidingExpiration="true" timeout="20">

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
<deny users="?"/>

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,

if (isMember)

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;
return false;

No comments:

Post a Comment