26

How to logout an user logged in with the ASP.Net Identity system?

I tried:

Authentication.SignOut();

But if I use this and then call an API marked with [Authorize] (adding the token as an header) It still returns me the data (instead of Unauthorized).

Liam
  • 27,717
  • 28
  • 128
  • 190
n0idea
  • 732
  • 1
  • 5
  • 14

2 Answers2

46

You need to call SignOut on the AuthenticationManager which you can get from the OWIN context.

var AuthenticationManager= HttpContext.GetOwinContext().Authentication;
AuthenticationManager.SignOut();
StuartQ
  • 3,739
  • 1
  • 26
  • 23
pranav rastogi
  • 4,124
  • 23
  • 23
  • 8
    just a quick fix: it should include `Current`: `HttpContext.Current.GetOwinContext().Authentication` – renakre Mar 01 '15 at 04:05
  • 7
    If you're inside an ASP.NET MVC controller you've got an instance property `HttpContext` from the base class, so you don't need `HttpContext.Current` in that scenario. – Matthew Walton Mar 23 '15 at 10:05
  • @MatthewWalton true, but if you are in let's say your custom HttpModule, then you certainly need `HttpContext.Current`... – netchkin Jun 12 '16 at 21:15
  • HttpContext.GetOwinContext().Authentication.SignOut(DefaultAuthenticationTypes.ApplicationCookie); would be more appropriate – DotNetGeek Jan 29 '18 at 10:53
  • 1
    Presumably this is pre .Net Core. Any idea how to do it in Core? – Auspex Oct 22 '21 at 11:21
  • @Auspex you could try to call HttpContext.SignOutAsync() – SebA Dec 10 '21 at 11:54
  • 1
    @Auspex just tried out some methods, in my case the SignOutAsync() Method of the SingInManager class worked – Seb Dec 10 '21 at 12:04
  • @Seb Yeah, I figured it out eventually, thanks – Auspex Dec 13 '21 at 11:19
1

In my case, because i had Authorize attribute in my AccountController with admin role at class level i had to put [AllowAnonymous] attribute to my logout method. May be a solution to you too.

Liam
  • 27,717
  • 28
  • 128
  • 190
O.Taaffe
  • 11
  • 1
  • 3
  • you could get an exception if an anonymous user tried to logout having the url. You should make a role only as a flag to a logged user. Same role to index logged user. – Leandro Bardelli Jan 18 '22 at 16:05