6

I'm making a new (empty template) ASP.NET MVC 5 application and I cannot logoff of this app. My logoff Action:

public ActionResult LogOff()
{
    if (User.Identity.IsAuthenticated)
    {
        //break here
    }
    try
    {
        AuthenticationManager.SignOut();
        if (User.Identity.IsAuthenticated || Request.IsAuthenticated)
        {
            //break here;
        }
    }
    return RedirectToAction("Login", "Account");
}

Startup class:

public partial class Startup
{
    public void ConfigureAuth(IAppBuilder app)
    {
        app.UseCookieAuthentication(new CookieAuthenticationOptions
        {
            AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
            LoginPath = new PathString("/Account/Login")
        });
        app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);
    }
}

Application Context:

 public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
 {
    public ApplicationDbContext()
        : base("DefaultConnection", false)
    {
    }
 } 

Connection string:

<connectionStrings>
<add name="DefaultConnection" connectionString="Server=.;Database=DataTest;Trusted_Connection=True;" providerName="System.Data.SqlClient" />
</connectionStrings>

The action LogOff() executes without problems and redirects me to the 'Login' action but I am still logged in. What is wrong with it?

molnarm
  • 9,856
  • 2
  • 42
  • 60
gog
  • 11,788
  • 23
  • 67
  • 129

7 Answers7

4

Try this:

[HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult LogOff()
    {
        //AuthenticationManager.SignOut();
        AuthenticationManager.SignOut(DefaultAuthenticationTypes.ApplicationCookie, DefaultAuthenticationTypes.ExternalCookie);
        Session.Abandon();
        return RedirectToAction("Login", "Account");
    }
Pedro Rainho
  • 4,234
  • 1
  • 19
  • 21
2
app.UseCookieAuthentication(new CookieAuthenticationOptions
            {
                AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
                LoginPath = new PathString("/Account/Login"),
                LogoutPath = new PathString("/Account/SignOut"),
                Provider = new CookieAuthenticationProvider
                {
                    // Enables the application to validate the security stamp when the user logs in.
                    // This is a security feature which is used when you change a password or add an external login to your account.  
                    OnValidateIdentity = SecurityStampValidator.OnValidateIdentity<ApplicationUserManager, ApplicationUser>(
                        validateInterval: TimeSpan.FromMinutes(30),
                        regenerateIdentity: (manager, user) => user.GenerateUserIdentityAsync(manager))
                }
            });      

^^Set the "LogoutPath" in Startup.Auth.cs to whatever route you desire

Neil King
  • 21
  • 1
1

Most of your code seems good to me. I would guess that something is wrong in your action method. Normally the only thing to do here is

public ActionResult LogOff()
{
    AuthenticationManager.SignOut();

    return RedirectToAction("Login", "Account");
}

I don't know if the if-blocks are crucial to your sign out process, but this two-liner is the only thing you have to do. If it is crucial you should check via the debugger if the SignOut method is hit.

Horizon_Net
  • 5,959
  • 4
  • 31
  • 34
  • Yes i know, i just put the other code to check if the user still authenticated. The problem is that the app seems to get the data from a cookie or something and then i still logged in after execute this action. – gog Jun 11 '14 at 16:34
  • 2
    Also, keep in mind that if you're using Chrome, it may not log you out: http://stackoverflow.com/questions/23632725/how-do-i-log-a-user-out-when-they-close-their-browser-or-tab-in-asp-net-mvc/23633068#23633068 – George Stocker Jun 11 '14 at 16:40
  • The cookie should be deleted after this method is executed (with the setup chosen in your startup class). Check with the developer tools of your browser if the cookie is still there. Regarding Chrome, I use it a lot for development and haven't had a problem yet when using Identity. – Horizon_Net Jun 11 '14 at 16:41
  • @George I too had the same problem and when i tested it with IE the problem went away. Chrome was not logging me off. – Igorski88 May 07 '19 at 03:54
0

This worked for me: create a route in your RouteConfig.cs like

 routes.MapRoute(
       "userlogout",
       "Account/Logout",
       new { controller = "Account", action = "LogOff" }
       );

And you can maintain the default logoff code in AccountController.cs or add the additions(like session.abandon(); etc) others have suggested But just as below should work

[HttpPost] 
[ValidateAntiForgeryToken]
public ActionResult LogOff()
{
    AuthenticationManager.SignOut();

    return RedirectToAction("Login", "Account");
}
Diin
  • 565
  • 11
  • 41
0

This seems to work well for me.

public ActionResult Logoff()
{
    HttpContext.Response.Cache.SetExpires(DateTime.UtcNow.AddMinutes(-1));
    HttpContext.Response.Cache.SetCacheability(HttpCacheability.NoCache);
    HttpContext.Response.Cache.SetNoStore();

    Session.Clear();
    Session.Abandon();
    Session.RemoveAll();
    FormsAuthentication.SignOut();
    return RedirectToAction("Index", "Home");
}
Andy Evans
  • 6,997
  • 18
  • 72
  • 118
0

In this case you could also do the following: Remove the [HttpPost] from your LogOff action and put the [HttpGet] instead. You only need to pass the AntiForgeryToken. But the question will be if this is a very secure way. more information available here: Using MVC3's AntiForgeryToken in HTTP GET to avoid Javascript CSRF vulnerability

[HttpGet] 
[ValidateAntiForgeryToken]
public ActionResult LogOff()
{
     AuthenticationManager.SignOut();
     return RedirectToAction("Login", "Account");
}
MDC
  • 56
  • 4
0

About ASP .Net MVC Logout not working:-

I had a problem where app hosted on IIS in production modes was not working right with chrome

though it was worked right while - using Visual Studio Dev hosting in all browsers - in production mode over IE

I had problems in Startup.Auth.CS. Make sure duplicate configurations are not there for following things

app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create);
app.UseCookieAuthentication((new CookieAuthenticationOptions(.....))
purvin
  • 61
  • 1
  • 2