simplemmembership和cookie用户数据兼容性

本文关键字:数据 兼容性 用户数 用户 cookie simplemmembership | 更新日期: 2023-09-27 18:13:08

我试图使用SimpleMembershipProvider为FormsAuthentication。现在,这个提供程序在内部创建一个formsath cookie,而不需要任何额外的userdata。

我想在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,并使用额外的userdata(序列化字符串)

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。上面的代码有什么问题吗?还是别的地方少了什么?

simplemmembership和cookie用户数据兼容性

找到了这个问题的答案,

查看链接

http://www.codetails.com/2013/05/25/using-claims-identity-with-simplemembership-in-asp-net-mvc/