octopusbones
octopusbones

Reputation: 89

MVC3 - Get Authenticated User's department name

In my app, I have a db table that contains a list of Users and a related table of Departments. As long as the User model is a property of the current object I'm operating on (retrieving from the db), I have no problems 'drilling down' to access the User's department name...or any other info that is a property of that User obj.

I'd like the ability to perform this same type of data access on the currently authenticated User....which is a totally different model apparently. Can anyone tell me if there is a way to append properties to the authenticated User model, or at least tie it to an existing object?

Thanks in advance for any help!

Update: I wanted to clarify that I'm talking about the User AuthCookie.

Upvotes: 1

Views: 937

Answers (2)

Daniel Liuzzi
Daniel Liuzzi

Reputation: 17147

There is a NuGet package called FormsAuthenticationExtensions that simplifies the code needed to insert custom data in your auth cookie.

For example, to store your data, you do:

var ticketData = new NameValueCollection
{
    { "name", user.FullName },
    { "emailAddress", user.EmailAddress }
};
new FormsAuthentication().SetAuthCookie(user.UserId, true, ticketData); 

And to get it back:

var ticketData = ((FormsIdentity) User.Identity).Ticket.GetStructuredUserData();
var name = ticketData["name"];
var emailAddress = ticketData["emailAddress"]; 

Upvotes: 4

brodie
brodie

Reputation: 5434

Yes you can add additional information to the the authentication cookie, but you need to generate the FormsAuthenticationTicket and cookie yourself.

A good example of setting the userdata is here

and an example of getting it back out is here

Upvotes: 1

Related Questions