Search code examples
asp.net-authentication

Recommended way to retrieve the current user identity in ASP.NET?


I'm reviewing an application currently experiencing problems with authentication (forms authentication is used combined with a custom way to retrieve the current user's profile) and I've noticed that the user's identity is retrieved using different methods:

  • Thread.CurrentPrincipal.Identity (on some http modules)
  • HttpContext.Current.User.Identity (on some http modules and also pages)
  • Page.User.Identity (on pages)

Is it safe to assume that the same value will always be returned by all methods?


Solution

  • HttpContext.Current.User.Identity (on some http modules and also pages) Page.User.Identity (on pages)

    Both of them return an Instance of IPrincipal

    Page.User uses the HttpContext object's User property to determine where the request originates

    The best methos is HttpContext.Current.User

    Thread.CurrentPrincipal.Identity won't show the right user if you use the Impersonation and it will give you the windows user details instead