Application_AuthenticateRequest in Global.asax

In Global.asax file:

protected void Application_AuthenticateRequest(object sender, EventArgs e) {

string cookieName = FormsAuthentication.FormsCookieName;
HttpCookie authCookie = Context.Request.Cookies[cookieName];

if (null == authCookie) {
// There is no authentication cookie.
return;
}

FormsAuthenticationTicket authTicket = null;
try {
authTicket = FormsAuthentication.Decrypt(authCookie.Value);
} catch (Exception ex) {
Logger.LogError(ex); // Log exception details (omitted for simplicity)
return;
}

if (null == authTicket) {
// Cookie failed to decrypt.
return;
}
FormsIdentity id = new FormsIdentity(authTicket);

// This principal will flow throughout the request.
string[] roles = new string[] { “user” };
MyPrincipal principal = new MyPrincipal (id, roles);
principal.User = LoginHelper.GetUserFromCookieString(authTicket.UserData);// Attach the new principal object to the current HttpContext object
Context.User = principal;
}

MyPrincipal .cs file:

public class MyPrincipal : GenericPrincipal {
string _user;

public AeDpPrincipal(IIdentity id, string[] roles)
: base(id, roles) {
}
public string User {
get { return _user; }
set { _user = value; }
}
}

LoginHelper.cs file:

public static class LoginHelper {

public static void LogIn(UserInfo user, bool rememberMe, bool redirect) {

if (user != null)
int ticketExpiration = Convert.ToInt32(ConfigurationManager.AppSettings[“loginTimeout”]);
FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1,
user.Id.ToString(),
DateTime.Now,
DateTime.Now.AddMinutes(ticketExpiration),
true,
user.SerializeForCookie(),
FormsAuthentication.FormsCookiePath);

// Encrypt the ticket.
string encTicket = FormsAuthentication.Encrypt(ticket);

// Create the cookie.
HttpCookie authCookie = new HttpCookie(FormsAuthentication.FormsCookieName, encTicket);
//authCookie.Expires = ticket.Expiration;
HttpContext.Current.Response.Cookies.Add(authCookie);

if (redirect)
HttpContext.Current.Response.Redirect(“~/ReservationList.aspx”);
}

public static string GetUserFromCookieString(string cookieString) {
string user = string.Empty;
string[] userParts = cookieString.Split(‘|’);
user =userParts[0];
return user;
}
}

Example for serialize business object
public string SerializeForCookie() {
StringBuilder sb = new StringBuilder();
sb.Append(this.Id);
sb.Append(“|“);
sb.Append(this.FirstName);
sb.Append(“|“);
sb.Append(this.LastName);
sb.Append(“|“);
sb.Append(this.Email);
return sb.ToString();
}

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s