FormsAuthenticationHelper.cs 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Web.Security;
  6. using System.Web;
  7. using System.Security.Principal;
  8. using System.Configuration;
  9. using System.Reflection;
  10. namespace Bowin.Common
  11. {
  12. public class FormsAuthenticationHelper
  13. {
  14. /// <summary>
  15. /// 创建登陆票据和存cookie
  16. /// 用于登陆成功后标记已登陆和用户信息
  17. /// </summary>
  18. /// <param name="httpContext">当前httpContext</param>
  19. /// <param name="cookieName">系统cookie名字</param>
  20. /// <param name="luserData">用户信息和CustomPrincipal对应</param>
  21. /// <returns></returns>
  22. public bool loginFormsAuthentication(HttpContextBase httpContext, string cookieName, List<string> luserData)
  23. {
  24. bool result = false;
  25. try
  26. {
  27. FormsAuthenticationTicket authTicket;
  28. authTicket = new FormsAuthenticationTicket(
  29. 1, //version
  30. luserData[0], //loginID
  31. DateTime.Now, // creation
  32. DateTime.Now.Add(FormsAuthentication.Timeout),//expired time
  33. false, //Persistent
  34. string.Join("|", luserData));
  35. //加密authTicket
  36. string data = FormsAuthentication.Encrypt(authTicket);
  37. HttpCookie cookies = new HttpCookie(cookieName, data);
  38. cookies.Domain = FormsAuthentication.CookieDomain;
  39. cookies.Secure = false;
  40. cookies.Path = FormsAuthentication.FormsCookiePath;
  41. cookies.Expires = authTicket.Expiration;
  42. httpContext.Response.Cookies.Add(cookies);
  43. result = true;
  44. }
  45. catch (Exception ex)
  46. {
  47. result = false;
  48. }
  49. return result;
  50. }
  51. /// <summary>
  52. /// 在Global.asax的Application_AuthenticateRequest事件使用
  53. /// 把客户端cockie解密存放于Page.User.(CustomPrincipal)对象
  54. /// </summary>
  55. /// <param name="httpContext">当前httpContext</param>
  56. /// <param name="cookieName">系统cookie名字</param>
  57. /// <param name="l_unvalidateUrl">排除掉需要验证登陆的url关健词</param>
  58. /// <param name="l_validateUrl">必须要验证登陆的url关健词</param>
  59. public void AuthenticateRequest(HttpContext httpContext, string cookieName, List<string> l_unvalidateUrl, List<string> l_validateUrl = null)
  60. {
  61. HttpCookie authCookie = httpContext.Request.Cookies[cookieName];
  62. if (authCookie == null)
  63. {
  64. string rurl = httpContext.Request.Path.ToLower();
  65. l_unvalidateUrl.Add(FormsAuthentication.LoginUrl.TrimStart('~'));
  66. if ((l_validateUrl != null && l_validateUrl.Any(w => rurl.IndexOf(w.ToLower()) >= 0))
  67. || !l_unvalidateUrl.Where(w => rurl.IndexOf(w.ToLower()) >= 0).Any())
  68. {
  69. httpContext.Response.Redirect(FormsAuthentication.LoginUrl + "?targetUrl=" + httpContext.Server.UrlEncode(httpContext.Request.Url.AbsoluteUri));
  70. }
  71. return;
  72. }
  73. FormsAuthenticationTicket authTicket = null; //票椐
  74. try
  75. {
  76. authTicket = System.Web.Security.FormsAuthentication.Decrypt(authCookie.Value); // Cookie 解密
  77. }
  78. catch (Exception ex)
  79. {
  80. //cookie解密报错清除
  81. authCookie.Expires = DateTime.Now.AddDays(-1);
  82. httpContext.Response.Cookies.Add(authCookie);
  83. httpContext.Response.Redirect(FormsAuthentication.LoginUrl);
  84. return;
  85. }
  86. string UserName = authTicket.UserData; //分解存在Cookie内的用户信息--
  87. FormsIdentity id = new FormsIdentity(authTicket);
  88. ICustomPrincipal principal = CustomPrincipalFactory.Create(id, UserName);
  89. httpContext.User = principal;
  90. }
  91. public void GetTicket(HttpContext httpContext, string url)
  92. {
  93. try
  94. {
  95. System.Web.Security.FormsAuthenticationTicket tk = ((System.Web.Security.FormsIdentity)httpContext.User.Identity).Ticket;
  96. string key = System.Web.Security.FormsAuthentication.Encrypt(tk); //每次加密后的字串都是不同的
  97. httpContext.Response.Redirect(url + "?ssologin=1&ticket=" + key); //跳转至下一页面
  98. }
  99. catch
  100. {
  101. httpContext.Response.Redirect(url + "?ssologin=0"); //跳转至下一页面
  102. }
  103. finally
  104. {
  105. httpContext.Response.End();
  106. }
  107. }
  108. public ICustomPrincipal ValidateTitcket(HttpContext httpContext, string ticket)
  109. {
  110. FormsAuthenticationTicket authTicket = null; //票椐
  111. try
  112. {
  113. authTicket = System.Web.Security.FormsAuthentication.Decrypt(ticket); // Cookie 解密
  114. }
  115. catch (Exception ex)
  116. {
  117. return null;
  118. }
  119. string UserName = authTicket.UserData; //分解存在Cookie内的用户信息--
  120. FormsIdentity id = new FormsIdentity(authTicket);
  121. ICustomPrincipal principal = CustomPrincipalFactory.Create(id, UserName);
  122. return principal;
  123. }
  124. }
  125. public interface ICustomPrincipal : IPrincipal
  126. {
  127. Guid UserID { get; set; }
  128. string LoginID { get; set; }
  129. string Name { get; set; }
  130. void ProcessData(IIdentity id, string data);
  131. }
  132. public class CustomPrincipalFactory
  133. {
  134. public static ICustomPrincipal Create(IIdentity id, string data)
  135. {
  136. string assemblyName = ConfigurationManager.AppSettings["CustomPrincipanAssembly"];
  137. string className = ConfigurationManager.AppSettings["CustomPrincipanClass"];
  138. Assembly assembly = Assembly.Load(assemblyName);
  139. ICustomPrincipal principal = (ICustomPrincipal)assembly.CreateInstance(className);
  140. principal.ProcessData(id, data);
  141. return principal;
  142. }
  143. }
  144. }