Feb 01 2010

ASP.NET FormsAuthentication – Persistant Ticket/Cookie

Tag: .NETMichael @ 12:19

Ich hatte einen recht eigenartigen Effekt bei FormsAuthentication in Zusammenhang mit einem persistant Authentickation Ticket.

Ein mit der Methode “FormsAuthentication.GetAuthCookie” erzeugtes Ticket war nur 30 Minuten gültig, obwohl ich überall gelesen habe, das ein so erzeugtes Ticket 50 Jahre gültig sein sollte.

Daher erstelle ich das Ticket jetzt von “Hand”, verschlüssele es und schreibe es in ein Cookie:

protected void Login_LoggedIn(object sender, EventArgs e)
{
	var ctrLogin = (Login) sender;
	var persistCheckBox = ctrLogin.FindControl("PersistCheckBox") as CheckBox;
	var isPersistent = persistCheckBox != null ? persistCheckBox.Checked : false;

	var authTicket = new FormsAuthenticationTicket(1, ctrLogin.UserName, DateTime.Now, isPersistent ? DateTime.Now.AddYears(2) : DateTime.Now.AddHours(1), isPersistent, "");
	var authCookie = new HttpCookie(FormsAuthentication.FormsCookieName, FormsAuthentication.Encrypt(authTicket)) {Expires = DateTime.Now.AddYears(2)};

	Response.Cookies.Add((authCookie));

	BayDirUser.SetUser(ctrLogin.UserName, ctrLogin.Password);

	if (_redirectUrl != null && !_redirectUrl.Equals(string.Empty))
		Response.Redirect(_redirectUrl, isPersistent);
	else
		Response.Redirect(FormsAuthentication.GetRedirectUrl(ctrLogin.UserName, isPersistent));
}

Jan 28 2010

ASP.NET FormsAuthentication – Logout

Tag: .NETMichael @ 13:00

ASP.NET FormsAuthentication – Logout

protected void LoggedOut(object sender, EventArgs e)
{
	FormsAuthentication.SignOut();
	HttpCookie authCookie = Context.Response.Cookies.Get(FormsAuthentication.FormsCookieName);

	if (authCookie != null)
		authCookie.Expires = DateTime.Now.AddYears(-1);

	Session.Abandon();

	Response.Redirect("~/default.aspx", true);
}