【问题标题】:FormsAuthenticationTicket Userdata still readable after encryption (asp.net MVC3 with forms Auth.)FormsAuthenticationTicket Userdata 加密后仍然可读(asp.net MVC3 with forms Auth。)
【发布时间】:2011-12-17 18:48:41
【问题描述】:

我正在使用新的 ASP.NET MVC3 框架并使用 FormsAuth 构建一个网站。用于保护网站。我将用户的角色存储在 FormsAuthenticationTicket 的 UserData 属性中(手动设置 cookie),然后在将其添加到 cookie 之前调用票证上的 encrypt 方法(参见下面的标准票证片段)。

if (Validate(model.UserName, model.Password))
                {                     
                    FormsAuthenticationTicket authTicket =  new FormsAuthenticationTicket(1,
                            model.UserName,
                            DateTime.Now,
                            DateTime.Now.AddMinutes(30),
                            false,
                            UserType.Administrator.ToString());
                    string encryptedTicket = FormsAuthentication.Encrypt(authTicket);
                    HttpCookie faCookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket);
                    Response.Cookies.Add(faCookie);   
                    return RedirectToAction("startpage", "mycontroller");
                }
            }     

现在我制作了一个自定义 AuthorizeAttribute,它能够检查用户是否 1. 已通过身份验证并且 2. 具有管理员角色(来自票证)。 (以下) 当具有属性注解的类中发生操作时,将调用该派生类的 AuthorizeCore 方法。

protected override bool AuthorizeCore(HttpContextBase httpContext)
        {
            if (httpContext == null)
            {
                throw new ArgumentNullException("httpContext");
            }
            IPrincipal user = httpContext.User;
            if (!user.Identity.IsAuthenticated)
            {
                return false;
            }
            string cookieName = FormsAuthentication.FormsCookieName;
            HttpCookie authCookie = httpContext.Request.Cookies[cookieName];
            if (authCookie == null)
                return false;

            FormsAuthenticationTicket authTicket =       FormsAuthentication.Decrypt(authCookie.Value);
            if (authTicket.UserData != UserType.Administrator.ToString())
                return false;
            return true;

所以这就是我感到困惑的地方。

当我跟踪正在执行的代码(使用有效凭据,在调试中)并检查在每一行上生成的变量的值时,encryptedTicket 在将其添加到响应cookie之前会很好地加密。

但是当我在调用(索引页面的)控制器时检查 AuthorizeCore 方法时,其获取的参数 HttpContext 包含所有未加密的票证,因此无需再解密票证阅读饼干。

为什么我在登录控制器中看到票证已成功加密,我将其发送回客户端,但是当我在 AuthorizeAdministrator 类中收到 httpcontext 时,它又全部未加密。

抱歉,问题/故事很长,可能有一个简单而简短的答案。 希望我的故事很清楚。

谢谢。

【问题讨论】:

  • 为什么不用User Roles来存储角色,而不是自己写,放到UserData字段中呢?

标签: asp.net-mvc asp.net-mvc-3


【解决方案1】:

Forms auth 需要在页面处理管道的早期解密 cookie,以确定用户是否已获得授权——此时它会填写 User.Identity 等详细信息。

【讨论】:

  • 谢谢,期待这样的事情,但想确定:)
猜你喜欢
  • 2014-03-08
  • 1970-01-01
  • 2013-11-28
  • 1970-01-01
  • 2012-08-21
  • 2013-01-29
  • 2011-10-22
  • 2011-04-15
  • 2013-05-11
相关资源
最近更新 更多