我正在尝试将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 中获取用户数据。上面的代码有什么问题吗?或者其他地方缺少什么?