ASP.NET - Form Authentication Tutorial

aspx.cs File's Content:
On Button Click for Login
protected void Button1_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection();
con.ConnectionString = "server={ServerName};uid={UserID};pwd={Password};database={DatabaseName}";
con.Open();
SqlCommand cm = new SqlCommand("select roles from users where username = '" + TextBox1.Text + "' and password = '" + TextBox2.Text + "'", con);
SqlDataReader dr = cm.ExecuteReader();
if (dr.Read())
{
FormsAuthenticationTicket tk = new FormsAuthenticationTicket(1, TextBox1.Text, DateTime.Now, DateTime.Now.AddMinutes (1),true, dr.GetString(0),FormsAuthentication.FormsCookiePath);
string hash = FormsAuthentication.Encrypt(tk);
HttpCookie Logincookie = new HttpCookie(FormsAuthentication.FormsCookieName,hash);
Response.Cookies.Add(Logincookie);
if (tk.IsPersistent)
{
HttpCookie ck = new HttpCookie( FormsAuthentication.FormsCookieName, hash);
ck.Expires = tk.Expiration;
Response.Cookies.Add(ck);
}
string returnUrl = Request.QueryString["ReturnUrl"];
if (returnUrl == null) returnUrl = "Main.aspx";
Response.Redirect(returnUrl);
}
else
{
Response.Write("The Username / Password not valid !");
}
con.Close();
dr.Close();
cm.Dispose();
}

Add These lines of code in Global.asax:
protected void Application_AuthenticateRequest(Object sender, EventArgs e)
{
if (HttpContext.Current.User != null)
{
if (HttpContext.Current.User.Identity.IsAuthenticated )
{
if (HttpContext.Current.User.Identity is FormsIdentity)
{
FormsIdentity id = (FormsIdentity)HttpContext.Current.User.Identity;
FormsAuthenticationTicket ticket = id.Ticket;
HttpCookie ck = new HttpCookie("ticket");
string userData = ticket.UserData;
string[] roles = userData.Split(',');
HttpContext.Current.User = new GenericPrincipal(id, roles);
}
}
}
}


Database:
CREATE TABLE users
(
username nvarchar(64) CONSTRAINT users_PK PRIMARY KEY,
password nvarchar(12,
roles nvarchar(64)
)
CREATE INDEX credentials ON users
(
username,
password
)
insert into users values('client','client','c')
insert into users values('admin','admin','a')
select * from users


Add These Lines in Web Config
Before </system.web>
<authentication mode="Forms">
<forms name="cookie" loginUrl="Default.aspx"> </forms>
</authentication>
<authorization>
<allow users="*">
</allow>

After </system.web> & before </configuration>
<location path="Admin"<>
<system.web>
<authorization>
<!-- Order and case are important below -->
<allow roles="a">
<deny users="*">
</deny>
</allow>
</authorization>
<location path="Client">
<system.web>
<authorization>
<!-- Order and case are important below -->
<allow roles="c,a">
<deny users="*">
</deny>
</allow>
</authorization>

1 comments:

Puneet Sharma said...

Really a nice collection of good featuer code snippts, please keep adding such up !