首页 新闻 会员 周边

MVC Form身份验证

1
悬赏园豆:100 [已关闭问题] 关闭于 2017-08-30 12:13

我有几台服务器,部署了同一个项目,只有其中一台服务器Form身份验证有问题:
登录帐号之后,再从票据里面找到登录用户,
HttpContext.Current.Request.IsAuthenticated=False;
(HttpContext.Current.User.Identity is FormsIdentity)=False;
所以无法通过验证。登录=>无法通过验证=>登录,这样循环。
但是在这台服务器自带的浏览器上访问项目。能通过验证,其他PC上访问就出现上面这个问题。

web.Config

 1  <system.web>
 2     <!--<authentication mode="None" />-->
 3     <compilation debug="true" targetFramework="4.5" />
 4     <httpRuntime targetFramework="4.5" maxQueryStringLength="102400"/>
 5     <authentication mode="Forms">
 6       <forms loginUrl="~/Home/Login" defaultUrl="~/Home/Index" timeout="2880" cookieless="UseUri" domain="Moqikaka.GameManage" protection="All" path="/"/>
 7     </authentication>
 8   </system.web>
 9   <system.webServer>
10     <modules>
11       <remove name="FormsAuthenticationModule" />
12     </modules>
13     <security>
14       <requestFiltering>
15         <requestLimits maxAllowedContentLength="3000000000" maxQueryString="102400" />
16       </requestFiltering>
17     </security>
18   </system.webServer>
View Code
 1   /// <summary>
 2     /// 身份验证实现
 3     /// </summary>
 4     public static class FormsAuthenticationService
 5     {
 6         /// <summary>
 7         /// 登陆
 8         /// </summary>
 9         /// <param name="user"></param>
10         /// <param name="createPersistentCookie"></param>
11         public static void SignIn(Models.LoginUserViewModel user, Boolean createPersistentCookie = true)
12         {
13             var now = DateTime.UtcNow.ToLocalTime();
14             var ticket = new FormsAuthenticationTicket(user.UserID,
15                 user.UserName,
16                 now,
17                 now.Add(FormsAuthentication.Timeout),
18                 createPersistentCookie,
19                string.IsNullOrEmpty(user.MenuId) ? " " : user.MenuId,
20                 FormsAuthentication.FormsCookiePath);
21             var encryptedTicket = FormsAuthentication.Encrypt(ticket);
22             var cookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket)
23             {
24                 HttpOnly = true,
25                 Path = FormsAuthentication.FormsCookiePath,
26                 Secure = false
27             };
28 
29             if (ticket.IsPersistent)
30             {
31                 cookie.Expires = ticket.Expiration;
32             }
33             cookie.Secure = FormsAuthentication.RequireSSL;
34             cookie.Path = FormsAuthentication.FormsCookiePath;
35 
36             HttpContext.Current.Response.Cookies.Remove(cookie.Name);
37             HttpContext.Current.Response.Cookies.Add(cookie);
38             HttpContext.Current.Session["LoginUserName"] = user.UserName;
39             HttpContext.Current.Session["LoginUserId"] = user.UserID;
40         }
41 
42         /// <summary>
43         /// 登出
44         /// </summary>
45         public static void SignOut()
46         {
47             FormsAuthentication.SignOut();
48         }
49 
50         /// <summary>
51         /// 获取验证的用户
52         /// </summary>
53         /// <returns></returns>
54         public static Models.LoginUserViewModel GetAuthenticatedUser()
55         {
56             if (HttpContext.Current == null || HttpContext.Current.Request == null ||
57                 !HttpContext.Current.Request.IsAuthenticated || !(HttpContext.Current.User.Identity is FormsIdentity))
58                 return null;
59 
60             var formsIdentity = (FormsIdentity)HttpContext.Current.User.Identity;
61 
62             //从票据中获取用户信息
63             var userData = formsIdentity.Ticket.UserData;
64 
65             if (String.IsNullOrWhiteSpace(userData))
66                 return null;
67 
68             var user = new Models.LoginUserViewModel() { UserID = formsIdentity.Ticket.Version, UserName = formsIdentity.Ticket.Name, MenuId = userData };
69 
70             return user;
71         }
72     }
View Code
 1  /// <summary>
 2     /// 登录权限验证
 3     /// </summary>
 4     public class CustomAuthorizeAttribute : AuthorizeAttribute
 5     {
 6         public new string[] Roles { get; set; }
 7         protected override bool AuthorizeCore(HttpContextBase httpContext)
 8         {
 9             string action = httpContext.Request.RequestContext.RouteData.Values["action"].ToString();
10             string controller = httpContext.Request.RequestContext.RouteData.Values["controller"].ToString();
11             //if ((new string[] { "Index", "login", "loginout", "vcode" }).Contains(action.ToLower()) && controller.ToLower() == "Home")
12             //    return true;
13 
14             var user = FormsAuthenticationService.GetAuthenticatedUser();
15             if (user == null || HttpContext.Current.Session["LoginUserName"] == null)
16                 return false;
17 
18             if (!httpContext.User.Identity.IsAuthenticated)
19                 return false;
20 
21             return true;
22         }
23 
24         public override void OnAuthorization(AuthorizationContext filterContext)
25         {
26             base.OnAuthorization(filterContext);
27             var user = FormsAuthenticationService.GetAuthenticatedUser();
28             if (user == null)
29                 return;
30 
31             string action = filterContext.ActionDescriptor.ActionName;
32             string controller = filterContext.ActionDescriptor.ControllerDescriptor.ControllerName;
33 
34             if (user.UserID != 1)
35             {
36                 var dicMenus = MenuProvider.GetMenuList();
37 
38                 var menus = new List<MenuItem>();
39                 foreach (var item in dicMenus)
40                 {
41                     if (item.Value.Controller != controller)
42                         continue;
43 
44                     if (item.Value.Action.ToLower() == action.ToLower())
45                         menus.Add(item.Value);
46                     else
47                     {
48                         if (string.IsNullOrWhiteSpace(item.Value.ChildAction))
49                             continue;
50                         var childaction = item.Value.ChildAction.ToLower().Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
51                         if (childaction.Contains(action.ToLower()))
52                             menus.Add(item.Value);
53                     }
54                 }
55 
56                 if ((menus == null || menus.Count() == 0))
57                 {
58                     filterContext.Result = new ContentResult() { Content = "此账号没有该权限" };                 
59                     Util.Log.LogUtil.Write(user.UserName + "没有访问[" + controller + "/" + action + "]的权限", Util.Log.LogType.Warn);
60                 }
61                 else
62                 {
63                     var menuPerList = user.MenuId.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
64                     if (menus.Where(p => !menuPerList.Contains(p.ID)).ToList().Count > 0)
65                     {
66                         filterContext.Result = new ContentResult() { Content = "此账号没有该权限." };                    
67                         Util.Log.LogUtil.Write(user.UserName + "没有访问[" + controller + "/" + action + "]的权限", Util.Log.LogType.Warn);
68                     }                  
69                 }
70             }
71         }
72 
73         /// <summary>
74         /// 从票据里面获取用户
75         /// </summary>
76         /// <param name="filterContext"></param>
77         protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
78         {
79             string returnUrl = filterContext.HttpContext.Request.RawUrl;
80             string redirectUrl = string.Format("~/Home/Login?ReturnUrl={0}", returnUrl);
81             filterContext.Result = new RedirectResult(redirectUrl, true);
82         }
83     }
View Code
< >
分享
所有回答(1)
0

第11行<remove name="FormsAuthenticationModule" />

神奇小饼干 | 园豆:109 (初学一级) | 2018-01-22 22:54
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册