【发布时间】:2013-05-12 12:57:53
【问题描述】:
我正在尝试将 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 中获取用户数据。上面的代码有什么问题吗?或者其他地方缺少什么?
【问题讨论】:
-
是您的 cookie 名称与
FormsAuthentication.FormsCookieName相同。 -
另外,在授权类中放置一个断点并检查请求中可用的cookie。
-
您能显示您的完整登录代码(不仅仅是 cookie 部分)吗?您的 cookie 可能会在某个时候被默认 cookie 覆盖。
标签: c# asp.net-mvc asp.net-mvc-4 simplemembership httpcookie