在研究FormsAuthentication几天之后,我决定将一个序列化对象存储在FormsAuth cookie的UserData属性中,并为HttpContext.Current.User使用自定义IPrincipal对象。
我发现的大多数指南都说要将IPrincipal对象强制转换为你的对象。我每次都会得到一个无效的强制转换异常。我做错了什么?
MyUserData
public class MyUserData
{
public long UserId { get; set; }
public string Username { get; set; }
public bool IsSuperUser { get; set; }
public string UnitCode { get; set; }
public string EmailAddress { get; set; }
public List<string> Roles { get; set; }
// Serialize
public override string ToString()
{
JavaScriptSerializer serializer = new JavaScriptSerializer();
string result = serializer.Serialize(this);
return result;
}
// Deserialize
public static MyUserData FromString(string text)
{
JavaScriptSerializer serializer = new JavaScriptSerializer();
return serializer.Deserialize<MyUserData>(text);
}
}
CustomPlatformPrincipal
public class MyCustomPrincipal : IPrincipal
{
public MyUserData MyUserData { get; set; }
public IIdentity Identity { get; private set; }
public MyCustomPrincipal(MyUserData myUserData)
{
MyUserData = myUserData;
Identity = new GenericIdentity(myUserData.Username);
}
public bool IsInRole(string role)
{
return MyUserData.Roles.Contains(role);
}
}
的Global.asax.cs
protected void Application_AuthenticateRequest(Object sender, EventArgs e)
{
HttpCookie authCookie = Context.Request.Cookies[FormsAuthentication.FormsCookieName];
if (authCookie == null || authCookie.Value == "")
{
return;
}
FormsAuthenticationTicket authTicket;
try
{
authTicket = FormsAuthentication.Decrypt(authCookie.Value);
}
catch
{
return;
}
if (Context.User != null)
{
// the from string deserializes the data
MyUserData myUserData = MyUserData.FromString(authTicket.UserData);
Context.User = new MyCustomPrincipal(myUserData);
}
}
我的页面
var myUserData = ((MyCustomPrincipal)(HttpContext.Current.User)).MyUserData;
// invalid cast exception (can't cast IPrincipal to MyCustomPrincipal)
我正在关注的文章:http://primaryobjects.com/CMS/Article147.aspx
所以似乎我获取数据的唯一方法是解密auth cookie,然后反序列化authCookie的userData字符串。
有什么建议吗?
更新
尝试遵循此SO问题的建议:Implementing a Custom Identity and IPrincipal in MVC
代码如下,但没有用。
[Serializable]
public class MyCustomPrincipal : IPrincipal, ISerializable
{
public CustomUserData CustomUserData { get; set; }
public IIdentity Identity { get; private set; }
//public MyCustomPrincipal (IIdentity identity) { Identity = identity; }
public MyCustomPrincipal(CustomUserData customUserData)
{
CustomUserData = customUserData;
Identity = new GenericIdentity(customUserData.Username);
}
public bool IsInRole(string role)
{
return PlatformUserData.Roles.Contains(role);
}
public void GetObjectData(SerializationInfo info, StreamingContext context)
{
if (context.State == StreamingContextStates.CrossAppDomain)
{
MyCustomPrincipal principal = new MyCustomPrincipal (this.CustomUserData );
info.SetType(principal.GetType());
System.Reflection.MemberInfo[] serializableMembers;
object[] serializableValues;
serializableMembers = FormatterServices.GetSerializableMembers(principal.GetType());
serializableValues = FormatterServices.GetObjectData(principal, serializableMembers);
for (int i = 0; i < serializableMembers.Length; i++)
{
info.AddValue(serializableMembers[i].Name, serializableValues[i]);
}
}
else
{
throw new InvalidOperationException("Serialization not supported");
}
}
}
答案 0 :(得分:2)
你是否在调试模式下运行?您可以在HttpContext.Current.User上设置断点,您将看到该用户当时的类型。 从您的Application_AuthenticateRequest方法,无法保证用户将是您期望的类型。在达到自定义类型设置之前,有许多退出点。 甚至这段代码:Context.User!= null。你的期望是错误的。我没有详细介绍Context.User,但是,根据您的上下文,您期望Context.User是您的自定义用户。所以有效的检查应该是:
var custom = Context.Current as MyCustomPrinciple;
if(custom == null)
{
// Your construct code here.
}
我强烈建议:您需要进入调试模式,以确切了解发生了什么。