Authorization.cs 3.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. using System.Web.Mvc;
  2. using System.Web.Security;
  3. using System.Collections.Generic;
  4. using System.Web;
  5. using System.Linq;
  6. using Bowin.Common;
  7. using Autofac;
  8. using EMISOnline.Web.Controls;
  9. using EMISOnline.Utility;
  10. using EMISOnline.CommonLogic.SystemServices;
  11. using EMISOnline.Utility.FormValidate;
  12. using EMISOnline.ViewModel.Account;
  13. namespace System
  14. {
  15. /// <summary>
  16. /// 表示需要用户登录才可以使用的特性
  17. /// 如果不需要处理用户登录,则请指定AllowAnonymousAttribute属性
  18. /// </summary>
  19. [AttributeUsage(AttributeTargets.Method | AttributeTargets.Class, Inherited = true, AllowMultiple = true)]
  20. public class AuthorizationAttribute : AuthorizeAttribute, IAuthorizationFilter
  21. {
  22. public void OnAuthorization(AuthorizationContext filterContext)
  23. {
  24. if (filterContext.HttpContext == null)
  25. {
  26. throw new Exception("此特性只适合于Web应用程序使用!");
  27. }
  28. else
  29. {
  30. FormsAuthenticationHelper fahelper = new FormsAuthenticationHelper();
  31. var cookieName = EMISOnline.Utility.Const.LOCAL_SETTING_LOGIN_COOKIENAME;
  32. if (Const.SSO_IS_SSO_LOGIN)
  33. {
  34. string rurl = filterContext.HttpContext.Request.Path.ToLower();
  35. var l_unvalidateUrl = Const.LOCAL_AUTH_EXCEPTURL.Concat(new List<string>() { FormsAuthentication.LoginUrl.TrimStart('~') });
  36. if (l_unvalidateUrl.Where(w => rurl.IndexOf(w.ToLower()) >= 0).Count() == 0)
  37. {
  38. if (filterContext.HttpContext.Request.Cookies[cookieName] == null)
  39. {
  40. var loginID = SSO.SSOLogin();
  41. if (loginID != "")
  42. {
  43. filterContext.Controller.LoginSureccessful(new LogOnModel { UserName = loginID }, loginID);
  44. }
  45. }
  46. }
  47. }
  48. fahelper.AuthenticateRequest(HttpContext.Current, cookieName, Const.LOCAL_AUTH_EXCEPTURL);
  49. var user = EMISOnline.Utility.FormValidate.CustomPrincipal.Current;
  50. if (user != null && user.RoleID == null)
  51. {
  52. using (var scope = AutofacHelper.Container.BeginLifetimeScope())
  53. {
  54. IUserServices userServices = scope.Resolve<IUserServices>();
  55. var role = userServices.GetUserRoles(user.UserID).FirstOrDefault();
  56. if (role != null)
  57. {
  58. user.RoleID = role.RoleID;
  59. HttpContext.Current.User = user;
  60. var userData = user.GetUserData();
  61. //刷新一下cookies,防止还要再读取数据库
  62. fahelper.loginFormsAuthentication(filterContext.HttpContext, cookieName, userData);
  63. }
  64. }
  65. }
  66. }
  67. }
  68. }
  69. }