Remember Me in Asp.net

In Web.Config File Put the lines Below..


<authentication mode="Forms">

<forms name="myFormAuth"

defaultUrl="~\Success.aspx"

loginUrl="login.aspx"

protection="All"

timeout="43200"

requireSSL="false"

slidingExpiration="true"

cookieless="AutoDetect" domain=""

enableCrossAppRedirects="false"

path="/"

/>

<credentials passwordFormat="SHA1" />



</forms>

</authentication>





In the Login.aspx use the following code.


protected override void OnInit(EventArgs e)
{
if (!IsPostBack && Session["user"] == null)
{
if (Request.Cookies["Cook"] != null)
{
HttpCookie cookie = Request.Cookies["Cook"];

string userId = cookie.Values["userId"].ToString();
string pwd = cookie.Values["pwd"].ToString();


int PrimaryRoleID = 0;


int LoginId = MyProject.ValidateLogin(userId, pwd, out PrimaryRoleID);

if (LoginId > 0)
{

Session["LoginId"] = LoginId;

Session["PrimaryRole"] = PrimaryRoleID;

}


doLogin(userId,pwd);
}
}
base.OnInit(e);
}



protected void Login1_Authenticate(object sender, AuthenticateEventArgs e)
{
int PrimaryRoleID = 0;


int LoginId = MyProject.ValidateLogin(Login1.UserName, Login1.Password, out PrimaryRoleID);

if (LoginId > 0)
{
e.Authenticated = true;

Session["LoginId"] = LoginId;

Session["PrimaryRole"] = PrimaryRoleID;

}

}
protected void Login1_LoggedIn(object sender, EventArgs e)
{

CheckBox chk = (CheckBox)Login1.FindControl("RememberMe");
if (chk != null && chk.Checked)
{

HttpCookie cookie = new HttpCookie("Cook");

cookie.Values.Add("userId", Login1.UserName);
cookie.Values.Add("pwd", Login1.Password);

cookie.Expires = DateTime.Now.AddYears(1);

Response.Cookies.Add(cookie);
}
doLogin(Login1.UserName,Login1.Password);

}

private void doLogin(string strUserID, string strPassword)
{
try
{
MyController objUser = new MyController();
MyProject.MyFactory.MYSecurity obj = new MyProject.MyFactory.MYSecurity();
obj = objUser.Login(strUserID, strPassword);

if (obj.LoginId.ToString() != null)
{
if (obj.LoginId.ToString() != "0")
{

Session["ModulePermission"] = obj.dtModulePermission;
Session["ChildEntity"] = obj.dtChildEntity;
Response.Redirect(@"Success.aspx");
}

}//if
}
catch (Exception ex)
{
throw ex;
}
}




In the MainMaster Page Use the following code for clearing cookies..

protected void lnkbtnLogout_Click(object sender, EventArgs e)
{

try
{
FormsAuthentication.SignOut();
Session.Abandon();
this.Session.Clear();

if (Response.Cookies["Cook"] != null)
{
Response.Cookies["Cook"].Expires = DateTime.Now.AddDays(-1);
}

Response.Redirect("~/Login.aspx");
Response.Cache.SetCacheability(HttpCacheability.Private);
Response.Cache.SetCacheability(HttpCacheability.NoCache);

}
catch (Exception ex)
{

throw ex;
}
}

No comments: