2013-05-12 25 views
0

我正在尝试使用SimpleMembershipProvider进行FormsAuthentication。现在,此提供程序在内部创建了一个FormsAuth cookie,但没有任何其他用户数据。简单会员和cookie userdata兼容性

我想包含在Cookie中,如用户ID,角色一些其他信息等

我有以下各项


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中获取用户数据。上面的代码有什么不对吗?还是在其他地方失踪?

+0

是你的cookie的名字一样'FormsAuthentication.FormsCookieName'。 – Saravanan 2013-05-12 13:13:15

+0

另外,在授权类中放置一个断点并检查请求中可用的cookie。 – Saravanan 2013-05-12 13:13:53

+0

你能显示完整的登录代码吗(不只是cookie部分)?有可能你的cookie在某些时候被默认的cookie覆盖。 – 2013-05-12 18:50:17

回答