Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 9186913
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 17, 20262026-06-17T19:38:45+00:00 2026-06-17T19:38:45+00:00

After researching FormsAuthentication for a few days, I decided to store a serialized object

  • 0

After researching FormsAuthentication for a few days, I decided to store a serialized object in the FormsAuth cookie’s UserData property and use a custom IPrincipal object for the HttpContext.Current.User.

Most of the guides I’ve found say to cast the IPrincipal object to your object. I get an invalid cast exception every time though. What am I doing wrong?

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

My Page

var myUserData = ((MyCustomPrincipal)(HttpContext.Current.User)).MyUserData;
// invalid cast exception (can't cast IPrincipal to MyCustomPrincipal)

Article I was following: http://primaryobjects.com/CMS/Article147.aspx

So it seems the only way I could get my data is to decrypt the auth cookie, then deserialize the authCookie’s userData string.

Any suggestions?

Update

Tried following the suggestions on this SO question: Implementing a Custom Identity and IPrincipal in MVC

Code is below, but it didn’t work.

[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");
        }
    }
}
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-17T19:38:47+00:00Added an answer on June 17, 2026 at 7:38 pm

    Did you run in the debug mode? You can put break point on HttpContext.Current.User, you will see what type the user was at that moment.
    And from your Application_AuthenticateRequest method, there is no guarantee that the User will be your expected type. There are many exit points before reaching your custom type setup.
    Even this code: Context.User != null. It was wrong with your expectation. I have not gone through the detail of the Context.User, however, in term of your context, you were expecting the Context.User was your custom user. So the valid check should be:

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

    My strongly suggestion is: you need to go in debug mode, to see exactly what was going on.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

The old version of the question is below, after researching more, I decided to
After researching a solution to this for three days, finally I gave up. Now
After researching a bit how the different way people slugify titles, I've noticed that
After researching various hosts, I still get the feeling that it is somewhat impossible
After some time researching and trying different things I still cannot get my @ExceptionHandler
As far as my understanding after reading and researching, the purpose of using salt
So after researching engines a lot I've been building a 2d framework for the
After researching windows mailsots for IPC within a local computer I'm a bit confused
After researching my options with regards to video support in Java, I stumbled across
After researching for a while I couldn't find out how to get the location

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.