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中獲取用戶數據。上面的代碼有什麼不對嗎?還是在其他地方失蹤?
是你的cookie的名字一樣'FormsAuthentication.FormsCookieName'。 – Saravanan 2013-05-12 13:13:15
另外,在授權類中放置一個斷點並檢查請求中可用的cookie。 – Saravanan 2013-05-12 13:13:53
你能顯示完整的登錄代碼嗎(不只是cookie部分)?有可能你的cookie在某些時候被默認的cookie覆蓋。 – 2013-05-12 18:50:17