1

What is the different between the following 3 methods to retrieve the claim?

Called in a ApiController:

((ClaimsIdentity) HttpContext.Current.User.Identity).Claims
((ClaimsIdentity) Thread.CurrentPrincipal.Identity).Claims

((ClaimsIdentity) User.Identity).Claims

The first two attributes have stored the same data but the last one has stored the data from the previous session.

This is done in the logout method:

UserCache.Instance.Clear();
FederatedAuthentication.SessionAuthenticationModule.SignOut();
HttpContext.Current.User = new GenericPrincipal(new GenericIdentity(string.Empty), null);

Update

Mixed WebForms, WebApi, MVC Application

Most of the application is build using WebForms.

Marko
  • 1,291
  • 1
  • 21
  • 37

1 Answers1

1

If you are working with WebApi, then HttpContext.Current should not be available directly (see this answer). So I'm guessing you are using MVC as well and you see MVC context there.

Thread.CurrentPrincipal is dangerous to use because it contains thread principle which can be something you never expect, like user that actually runs IIS (AppPool user). Most of the time it is what you think, but sometimes it is not. And this will cause you endless bug-chasing that you can never recreate yourself.

User.Identity as ClaimsIdentity is the correct way to get what you need and it is used in the default template from VS. However if you see the data from "previous session" - means your cookies are not cleared properly. And the way you sign-out user looks suspicious:

  1. What is UserCache.Instance?
  2. SignOut method does not actually sign out user until the request is complete. So if you call this and then check for user identity within the same request, you'll see the same identity intact.
  3. Assigning HttpContext.Current.User will not give you much within the request. See very first point if we are talking about pure WebAPI.

Default sign-out is done via IAuthenticationManager

    private IAuthenticationManager Authentication
    {
        get { return Request.GetOwinContext().Authentication; }
    }

    [Route("Logout")]
    public IHttpActionResult Logout()
    {
        Authentication.SignOut(CookieAuthenticationDefaults.AuthenticationType);
        return Ok();
    }

Try this and then adjust for your needs.

Community
  • 1
  • 1
trailmax
  • 34,305
  • 22
  • 140
  • 234
  • UserCache.Instance is created by us to hold some data. I cannot logout in ApiController because I want to avoid to rewrite our legacy code if possible. Is it possible to logout in the Global.asax.cs? Is it allowed to create a instance of a ApiController and call one of its methods? – Marko Feb 10 '15 at 08:12
  • No, logging out in Global.Asax is not possible. And if possible, should not be done there. I'm afraid you'll have to modify controllers to allow for logging-out. – trailmax Feb 10 '15 at 09:01