Simplemembership和cookie userdata兼容性

时间:2013-05-12 12:57:53

标签: c# asp.net-mvc asp.net-mvc-4 simplemembership httpcookie

我正在尝试将 SimpleMembershipProvider 用于FormsAuthentication。现在,此提供程序在内部创建一个FormsAuth cookie,而无需任何其他用户数据。

我想在Cookie中包含一些其他信息,例如UserId,Role

我已实施以下 -


public class MyAuthorizeAttribute : AuthorizeAttribute
{
    protected override bool AuthorizeCore(HttpContextBase httpContext)
    {
        var isAuthorized = base.AuthorizeCore(httpContext);
        if (isAuthorized)
        {
            var formsCookie = httpContext.Request.Cookies[FormsAuthentication.FormsCookieName];
            var identity = new AppUserIdentity(string.Empty, true);
            if (formsCookie != null)
            {
                var cookieValue = FormsAuthentication.Decrypt(formsCookie.Value);
                if (cookieValue != null && !string.IsNullOrEmpty(cookieValue.UserData))
                {
                    var cookieData = SerializerXml.Deserialize<UserNonSensitiveData>(cookieValue.UserData);
                    identity = new AppUserIdentity(cookieValue.Name, cookieData.UserId, true);
                }
                else if (cookieValue != null)
                {
                    //TODO: Find out technique to get userid value here
                    identity = new AppUserIdentity(cookieValue.Name, null, true);
                }
            }

            var principal = new AppUserPrincipal(identity);
            httpContext.User = Thread.CurrentPrincipal = principal;
        }
        return isAuthorized;
    }
}

此属性在所有必需的控制器方法上进行修饰。当用户注册或登录网站时,我正在更新cookie以及其他用户数据(序列化字符串)

var newticket = new FormsAuthenticationTicket(ticket.Version,
                                                      ticket.Name,
                                                      ticket.IssueDate,
                                                      ticket.Expiration,
                                                      ticket.IsPersistent,
                                                      userdata,
                                                      ticket.CookiePath);

        // Encrypt the ticket and store it in the cookie
        cookie.Value = FormsAuthentication.Encrypt(newticket);
        cookie.Expires = newticket.Expiration.AddHours(24);

        Response.Cookies.Set(cookie);

但是,在MyAuthorizeAttribute中,它永远不会在cookie中获取userdata。上面的代码有什么问题吗?或者其他地方遗漏的东西?

1 个答案:

答案 0 :(得分:0)