Example for Forms Authentication

Manimaddu
Posted by Manimaddu under ASP.NET category on | Points: 40 | Views : 1310
Hi All...
This is one of the example for Form Authentication in Asp.Net

LoginPage.aspx


<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Login.aspx.cs" Inherits="Login" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>Untitled Page</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<table><tr><td><table>
<tr>
<td >
</td>
<td >
</td>
</tr>
<tr>
<td >
UserID</td>
<td >
<asp:TextBox ID="txtUserid" runat="server"></asp:TextBox></td>
</tr>
<tr>
<td >
Password</td>
<td >
<asp:TextBox ID="txtPassword" runat="server"></asp:TextBox></td>
</tr>
<tr>
<td >
</td>
<td >
<asp:CheckBox ID="chkRemeberMe" runat="server" Text="Remember me next time." /></td>
</tr>
<tr>
<td >
</td>
<td >
<asp:Label ID="lblMessage" runat="server" ForeColor="Maroon"></asp:Label></td>
</tr>
<tr>
<td >
</td>
<td >
<asp:Button ID="btnLogin" runat="server" OnClick="btnLogin_Click" Text="Login" /></td>
</tr>
</table></td><td><asp:LoginName ID="LoginName1" FormatString="You are Logged in as <b>{0}</b>" runat="server" /></td></tr></table>


</div>
</form>
</body>
</html>


LoginPage.aspx.cs:


using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

public partial class Login : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (User.Identity.IsAuthenticated && Request.QueryString["ReturnUrl"] != null)
{
Response.Redirect("NotAuthorized.aspx");
}

lblMessage.Text = "";
}
protected void btnLogin_Click(object sender, EventArgs e)
{
User _user = new User();
DBOperations dbo = new DBOperations();
_user = dbo.CheckUser(txtUserid.Text);
if (_user != null)
{
if (_user.Password == txtPassword.Text)
{
FormsAuthenticationTicket Authticket = new FormsAuthenticationTicket(
1,
txtUserid.Text,
DateTime.Now,
DateTime.Now.AddMinutes(30),
chkRemeberMe.Checked,
_user.Role,
FormsAuthentication.FormsCookiePath);

string hash = FormsAuthentication.Encrypt(Authticket);

HttpCookie Authcookie = new HttpCookie(FormsAuthentication.FormsCookieName, hash);

if (Authticket.IsPersistent) Authcookie.Expires = Authticket.Expiration;

Response.Cookies.Add(Authcookie);

string returnUrl = Request.QueryString["ReturnUrl"];
if (returnUrl == null) returnUrl = "/";

Response.Redirect(returnUrl);
}
else
{
lblMessage.Text = "Password does'nt match.";
}
}
else
{
lblMessage.Text = "User not exists.";
}
}
}


Thank You...

Comments or Responses

Login to post response