Fruitbat
Fruitbat

Reputation: 774

Why is the asp.net membership UserID not stored in the authentication ticket?

I was looking at linking my own User table to the asp.net membership by storing my userid (int) in the UserData area of the authentication cookie (Storing and accessing a legacy UserID in asp.net membership).

As my application is for my own use and also to help me learn asp/c#, I thought it might be a good idea to compare the effort of tweaking membership to fit my database with the reverse (i.e. use membership out of the box and adjust my database accordingly).

If I convert my database to use guid (uniqueidentifier) UserIDs as foreign keys in all my user related tables, then I still need a way to make the UserID easily accessible to my application. The accepted way to get the UserID seems to be like so:

Guid userID = (Guid)Membership.GetUser().ProviderUserKey;

Now, if I understand correctly, this involves a read of the database. Perhaps I'm being picky, but it seems a bit unnecessary on every request. I would be inclined to put it in the ticket. I can't see any problem with putting a PK value in the ticket (guid or int). Is there a security risk? Membership seems to be happy using the UserName as a key rather than the surrogate. Which begs the question - why didn't they put UserID in the ticket?

Upvotes: 4

Views: 725

Answers (2)

Bilal
Bilal

Reputation: 182

You can always write your own UserPrinciple implementing IPrinciple which can give you the userID once and this can be called anywhere in the application without actually hitting the database. Then you can use the userId in cookie if you still want to.

Upvotes: 0

goTo-devNull
goTo-devNull

Reputation: 9372

Cookies and URLs have practical maximum lengths - the FormsAuthenticationTicket.UserData documentation states:

"You should limit the amount of data stored in the UserData property. You must ensure that the size of the UserData property does not result in an invalid cookie or an excessively long URL."

ASP.NET can be configured to use cookieless forms authentication, which stores the authentication ticket in the URL. In this case the ASP.NET ISAPI filter also has to do a bit of extra work to strip the ticket information then rewrite the URL.

So part of the reason can probably be attributed to a trade-off of keeping the default cookie/URL lengths to a minimum - storing an encrypted, serialized Guid in the ticket would increase the length of the cookie/URL, and also further limit (granted not by much) the amount of data you can store in UserData.

Upvotes: 1

Related Questions