Willcode4cash

Forms Authenication

Aug 14th, 2016
74
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.34 KB | None | 0 0
  1. /*
  2.  *  Located in Global.asax.cs
  3.  */
  4.  
  5. protected void Application_AuthenticateRequest(Object sender, EventArgs e)
  6. {
  7.         var userData
  8.  
  9.         if (HttpContext.Current.User == null) return;
  10.         if (!HttpContext.Current.User.Identity.IsAuthenticated) return;
  11.         var id = HttpContext.Current.User.Identity as FormsIdentity;
  12.         if (id == null) return;
  13.  
  14.         FormsAuthenticationTicket ticket = id.Ticket;
  15.         string userData = ticket.UserData;
  16.         string[] roles = userData.Split(',');
  17.         HttpContext.Current.User = new GenericPrincipal(id, roles);
  18. }
  19.  
  20. /*
  21.  *  Located in an accessible extension class
  22.  */
  23.  
  24. public static bool BuildCookie(this Userprofile userprofile, bool remember = true)
  25. {
  26.     try
  27.     {
  28.         var roles = "A comma delimited string of roles";
  29.  
  30.         FormsAuthentication.Initialize();
  31.         var ticket = new FormsAuthenticationTicket(1,
  32.             userprofile.UserprofileID.ToString(),
  33.             DateTime.Now,
  34.             DateTime.Now.AddDays(90),
  35.             remember,
  36.             roles,
  37.             FormsAuthentication.FormsCookiePath);
  38.  
  39.         var hashedTicket = FormsAuthentication.Encrypt(ticket);
  40.         var cookie = new HttpCookie(FormsAuthentication.FormsCookieName, hashedTicket);
  41.         if (ticket.IsPersistent) cookie.Expires = ticket.Expiration;
  42.         HttpContext.Current.Response.Cookies.Add(cookie);
  43.         return true;
  44.     } catch (Exception)
  45.     {
  46.         return false;
  47.     }
  48. }
Add Comment
Please, Sign In to add comment