县级监管平台

FormsPrincipal.cs 2.5KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Security.Principal;
  5. using System.Web;
  6. using System.Web.Script.Serialization;
  7. using System.Web.Security;
  8. namespace CallCenterApi.Interface.Models.Common
  9. {
  10. public class FormsPrincipal<TUserData> : IPrincipal
  11. where TUserData : class, new()
  12. {
  13. private IIdentity _identity;
  14. private TUserData _userData;
  15. public FormsPrincipal(FormsAuthenticationTicket ticket, TUserData userData)
  16. {
  17. if (ticket == null)
  18. throw new ArgumentNullException("ticket");
  19. if (userData == null)
  20. throw new ArgumentNullException("userData");
  21. _identity = new FormsIdentity(ticket);
  22. _userData = userData;
  23. }
  24. public TUserData UserData
  25. {
  26. get { return _userData; }
  27. }
  28. public IIdentity Identity
  29. {
  30. get { return _identity; }
  31. }
  32. public bool IsInRole(string role)
  33. {
  34. // 把判断用户组的操作留给UserData去实现。
  35. IPrincipal principal = _userData as IPrincipal;
  36. if (principal == null)
  37. throw new NotImplementedException();
  38. else
  39. return principal.IsInRole(role);
  40. }
  41. /// <summary>
  42. /// 执行用户登录操作
  43. /// </summary>
  44. /// <param name="loginName">登录名</param>
  45. /// <param name="userData">与登录名相关的用户信息</param>
  46. /// <param name="expiration">登录Cookie的过期时间,单位:分钟。</param>
  47. public static string GetCookieValue(string loginName, TUserData userData)
  48. {
  49. if (string.IsNullOrEmpty(loginName))
  50. throw new ArgumentNullException("loginName");
  51. if (userData == null)
  52. throw new ArgumentNullException("userData");
  53. // 1. 把需要保存的用户数据转成一个字符串。
  54. string data = null;
  55. if (userData != null)
  56. data = (new JavaScriptSerializer()).Serialize(userData);
  57. // 2. 创建一个FormsAuthenticationTicket,它包含登录名以及额外的用户数据。
  58. FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(
  59. 2, loginName, DateTime.Now, DateTime.Now.AddDays(1), true, data);
  60. // 3. 加密Ticket,变成一个加密的字符串。
  61. return FormsAuthentication.Encrypt(ticket);
  62. }
  63. }
  64. }