giammin

WebAuthHelper

Jan 30th, 2013
709
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 4.75 KB | None | 0 0
  1.    public class AuthHelper
  2.     {
  3.         protected readonly Logger Logger = LogManager.GetCurrentClassLogger();
  4.         public HttpContext CurrentContext { get; set; }
  5.         public bool IsAuthenticated { get { return CurrentContext.User != null && CurrentContext.User.Identity.IsAuthenticated; } }
  6.  
  7.         public AuthHelper(HttpContext currentContext)
  8.         {
  9.             if (currentContext == null)
  10.             {
  11.                 throw new ArgumentNullException("currentContext");
  12.             }
  13.             CurrentContext = currentContext;
  14.         }
  15.         public AuthHelper():this(HttpContext.Current) { }
  16.  
  17.         public bool IsInRole(string roleName)
  18.         {
  19.             return IsAuthenticated && CurrentContext.User.IsInRole(roleName);
  20.         }
  21.  
  22.         public void Logout(bool redirectToRoot)
  23.         {
  24.             Logger.Debug("AuthHelper.Logout: Logout current user, redirect to root:{0}", redirectToRoot);
  25.             FormsAuthentication.SignOut();
  26.  
  27.             //sometimes session could be null EX:  Server.Execute
  28.             if (CurrentContext.Session != null)
  29.             {
  30.                 CurrentContext.Session.Abandon();
  31.             }
  32.  
  33.             HttpCookie c = CurrentContext.Request.Cookies[FormsAuthentication.FormsCookieName];
  34.             if (c != null)
  35.             {
  36.                 c.Expires = DateTime.Now.AddDays(-1);
  37.                 CurrentContext.Response.Cookies.Add(c);
  38.             }
  39.             if (redirectToRoot)
  40.             {
  41.                 CurrentContext.Response.Clear();
  42.                 CurrentContext.Response.Redirect("~/",false);
  43.                 CurrentContext.ApplicationInstance.CompleteRequest();
  44.             }
  45.         }
  46.        
  47.         public string GetLoggedUserName()
  48.         {
  49.             string rtn = string.Empty;
  50.  
  51.             if (CurrentContext.User != null)
  52.             {
  53.                 if (CurrentContext.User.Identity.IsAuthenticated)
  54.                 {
  55.                     var gp = CurrentContext.User as GenericPrincipal;
  56.                     if (gp!=null)
  57.                     {
  58.                         rtn = gp.Identity.Name;
  59.                     }
  60.                 }
  61.             }
  62.             Logger.Debug("AuthHelper.GetLoggedUserName: {0}",rtn);
  63.             return rtn;
  64.         }
  65.  
  66.         public void AuthenticateUser(string userName, string roles)
  67.         {
  68.             Logger.Debug("AuthHelper.AuthenticateUser: userName:{0} roles:{1}", userName, roles);
  69.  
  70.             if (string.IsNullOrEmpty(userName))
  71.             {
  72.                 throw new ArgumentNullException("userName", "AuthHelper.AuthenticateUser: userName cannot be null");
  73.             }
  74.  
  75.             Configuration config = WebConfigurationManager.OpenWebConfiguration("~");
  76.             var authenticationSection = (AuthenticationSection)config.GetSection("system.web/authentication");
  77.  
  78.             if (authenticationSection.Mode != AuthenticationMode.Forms)
  79.             {
  80.                 throw new NotImplementedException(string.Format("AuthHelper cannot handle {0}", authenticationSection.Mode));
  81.             }
  82.            
  83.             var timeout = authenticationSection.Forms.Timeout;            
  84.             var ticket = new FormsAuthenticationTicket(
  85.                     1,
  86.                     userName,
  87.                     DateTime.Now,
  88.                     DateTime.Now.Add(timeout),
  89.                     true,
  90.                     roles,
  91.                     FormsAuthentication.FormsCookiePath);
  92.  
  93.             string hash = FormsAuthentication.Encrypt(ticket);
  94.  
  95.             var cookie = new HttpCookie(FormsAuthentication.FormsCookieName, hash);
  96.             cookie.Domain = FormsAuthentication.CookieDomain;
  97.  
  98.             if (ticket.IsPersistent)
  99.             {
  100.                 cookie.Expires = ticket.Expiration;
  101.             }
  102.             CurrentContext.Response.Cookies.Add(cookie);
  103.             SetIdentity(CurrentContext, new FormsIdentity(ticket), roles);
  104.         }
  105.  
  106.         public static void AuthenticateRequest(HttpContext httpContext)
  107.         {
  108.             if (httpContext.User != null)
  109.             {
  110.                 if (httpContext.User.Identity.IsAuthenticated)
  111.                 {
  112.                     var formsIdentity = httpContext.User.Identity as FormsIdentity;
  113.                     if (formsIdentity != null)
  114.                     {
  115.                         SetIdentity(httpContext, formsIdentity, formsIdentity.Ticket.UserData);
  116.                     }
  117.                 }
  118.             }
  119.         }
  120.  
  121.         private static void SetIdentity(HttpContext httpContext, IIdentity identity, string userRoles)
  122.         {
  123.             string[] roles = userRoles.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
  124.             httpContext.User = new GenericPrincipal(identity, roles);
  125.         }
  126.     }
Advertisement
Add Comment
Please, Sign In to add comment