2

I have implemented a custom IPrincipal that I set in

 protected void Application_PostAuthenticateRequest(Object sender, EventArgs args)

by doing

Context.User = GetCustomPrincipal(User.Identity);
Thread.CurrentPrincipal = Context.User;

But my custom principal hits the database and gets custom information about the user. I don't want it hitting the database repeatedly for every request.

What is the best way to cache this? I was thinking of storing it in the Session, is that a good idea?

EDIT: Stupid me. Session is not even available in this method, should have tested before posting the question.

But question still remains..

tereško
  • 58,060
  • 25
  • 98
  • 150
lahsrah
  • 9,013
  • 5
  • 37
  • 67
  • See also: http://stackoverflow.com/questions/1064271/asp-net-mvc-set-custom-iidentity-or-iprincipal/1064345#1064345 – John Rasch Jun 14 '11 at 02:53

1 Answers1

1

The standard approach is to store the data in the auth cookie. If you aren't using cookies, you can store the data in session.

Ethan Cabiac
  • 4,943
  • 20
  • 36
  • 2
    Cookie!? That's not a good idea. This is private data about the user and so it shouldn't be on the client side. – lahsrah Jun 14 '11 at 02:40
  • @sylon - the auth cookie is encrypted. You also don't have to store the principal itself, just the data you need to reconstruct it without going to the database. – Ethan Cabiac Jun 14 '11 at 02:45
  • Yes but some of this data is private. Like the roles the user belongs to in my site's custom roles model and a bunch of information about the user. Only thing I keep in the cookie is authentication token and preferences like the language preference. – lahsrah Jun 14 '11 at 02:47
  • Again - if you use an encryped, signed auth cookie then the data in the cookie can neither be viewed or tampered. – Ethan Cabiac Jun 14 '11 at 03:01
  • 3
    @sylon if someone is able to decrypt a cookie, they can encrypt one too. This is a greater security risk as a user can simply fake a login cooke at anytime for any user. – MerickOWA Jun 14 '11 at 03:10
  • The server encrypts and signs the cookie. The user passes the cookie to the server on each request, but only the server can decrypt the cookie. If you do not use persistent cookies, then the cookies will only be valid for the duration of the session. See here: http://support.microsoft.com/kb/910443 for how the forms authentication cookie works. – Ethan Cabiac Jun 14 '11 at 03:15
  • 1
    Storing private data client-side is always a risk. Encrypting it might make it safe *today*, but if a new vulnerability (such as [this one](http://stackoverflow.com/q/3720720/88709)) is discovered tomorrow, suddenly your private data is not private anymore, and your system is open to exploits. – Daniel Liuzzi May 24 '12 at 14:13