0

在研究 FormsAuthentication 几天后,我决定在 FormsAuth cookie 的 UserData 属性中存储一个序列化对象,并为 HttpContext.Current.User 使用自定义 IPrincipal 对象。

我发现的大多数指南都说将 IPrincipal 对象转换为您的对象。不过,我每次都会得到一个无效的演员表异常。我究竟做错了什么?

我的用户数据

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);
    }
}

全球.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 问题的建议:在 MVC 中实现自定义身份和 IPrincipal

代码如下,但它不起作用。

[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");
        }
    }
}
4

1 回答 1

2

你是在调试模式下运行的吗?您可以在 HttpContext.Current.User 上设置断点,您将看到当时用户的类型。而且从您的 Application_AuthenticateRequest 方法中,不能保证 User 将是您的预期类型。在达到您的自定义类型设置之前,有许多退出点。甚至这段代码:Context.User != null。你的期望是错误的。我没有详细介绍 Context.User,但是,就您的上下文而言,您期望 Context.User 是您的自定义用户。所以有效的检查应该是:

var custom = Context.Current as MyCustomPrinciple;
if(custom == null)
{
// Your construct code here.
}

我强烈的建议是:你需要进入调试模式,看看到底发生了什么。

于 2013-01-25T02:12:43.397 回答