我在使用自定义主体的MVC应用程序中实现“记住我”功能时遇到了困难。我已经将问题归结为ASP.NET未检索到我的身份验证cookie。下面是来自Google Chrome的快照:
我的应用程序使用自定义IPrincipal。BusinessPrincipalBase是一个实现了IPrincipal的CSLA对象。以下是该代码:
该应用程序还使用了自定义成员资格提供程序。以下是其代码。
我认为这些都与问题无关,因为底线是Request.Cookies没有返回身份验证cookie。这是否与cookie的大小有关?我听说cookie的大小存在问题。
更新:看起来问题围绕子域名展开。该站点被托管在一个子域中,而cookie域留空了。有人能给我指点如何使auth cookie在所有域名(例如http://example.com、http://www.example.com和http://sub.example.com)中工作吗?
显示了在控制器操作中设置并放置在ViewData中供视图读取的Request.Cookies的结果。请注意,.ASPXAUTH cookie丢失了。
显示了Chrome开发人员工具中的结果。您可以在这里看到.ASPXAUTH。
我的应用程序使用自定义IPrincipal。BusinessPrincipalBase是一个实现了IPrincipal的CSLA对象。以下是该代码:
[Serializable()]
public class MoralePrincipal : BusinessPrincipalBase
{
private User _user;
public User User
{
get
{
return _user;
}
}
private MoralePrincipal(IIdentity identity) : base(identity)
{
if (identity is User)
{
_user = (User)identity;
}
}
public override bool Equals(object obj)
{
MoralePrincipal principal = obj as MoralePrincipal;
if (principal != null)
{
if (principal.Identity is User && this.Identity is User)
{
return ((User)principal.Identity).Equals(((User)this.Identity));
}
}
return base.Equals(obj);
}
public override int GetHashCode()
{
return base.GetHashCode();
}
public static bool Login(string username, string password)
{
User identity = User.Fetch(username, password);
if (identity == null || !identity.IsAuthenticated)
{
identity = (User)User.UnauthenicatedIdentity;
}
MoralePrincipal principal = new MoralePrincipal(identity);
Csla.ApplicationContext.User = principal;
Context.Current.User = identity;
return identity != null && identity.IsAuthenticated;
}
public static void Logout()
{
IIdentity identity = User.UnauthenicatedIdentity;
MoralePrincipal principal = new MoralePrincipal(identity);
ApplicationContext.User = principal;
Context.Current.User = identity as User;
}
public override bool IsInRole(string role)
{
if (Context.Current.User == null || Context.Current.Project == null)
{
return false;
}
string userRole = Context.Current.User.GetRole(Context.Current.Project.Id);
return string.Compare(role, userRole, true) == 0;
}
该应用程序还使用了自定义成员资格提供程序。以下是其代码。
public class MoraleMembershipProvider : MembershipProvider
{
public override bool ValidateUser(string username, string password)
{
bool result = MoralePrincipal.Login(username, password);
HttpContext.Current.Session["CslaPrincipal"] = ApplicationContext.User;
return result;
}
#region Non-Implemented Properties/Methods
public override string ApplicationName
{
get
{
return "Morale";
}
set
{
throw new NotImplementedException();
}
}
// Everything else just throws a NotImplementedException
#endregion
}
我认为这些都与问题无关,因为底线是Request.Cookies没有返回身份验证cookie。这是否与cookie的大小有关?我听说cookie的大小存在问题。
更新:看起来问题围绕子域名展开。该站点被托管在一个子域中,而cookie域留空了。有人能给我指点如何使auth cookie在所有域名(例如http://example.com、http://www.example.com和http://sub.example.com)中工作吗?