Windows Authentication Logout / SigninwithDifferent User

952 Views Asked by At

I am using windows authentication in ASP.NET MVC.

I want to Logout? So I researched and found the following

The code is based on decompiling the Microsoft.TeamFoundation.WebAccess which has the "Sign in as a different User" function.

public ActionResult LogOut()
{
    HttpCookie cookie = Request.Cookies["TSWA-Last-User"];
    if(User.Identity.IsAuthenticated == false || cookie == null || StringComparer.OrdinalIgnoreCase.Equals(User.Identity.Name, cookie.Value))
    {
        string name = string.Empty;

        if(Request.IsAuthenticated)
        {
            name = User.Identity.Name;
        }

        cookie = new HttpCookie("TSWA-Last-User", name);
        Response.Cookies.Set(cookie);

        Response.AppendHeader("Connection", "close");
        Response.StatusCode = 0x191;
        Response.Clear();
        //should probably do a redirect here to the unauthorized/failed login page
        //if you know how to do this, please tap it on the comments below
        Response.Write("Unauthorized. Reload the page to try again...");
        Response.End();

        return RedirectToAction("Index");
    }

    cookie = new HttpCookie("TSWA-Last-User", string.Empty)
    {
        Expires = DateTime.Now.AddYears(-5)
    };

    Response.Cookies.Set(cookie);

    return RedirectToAction("Index");

}

Is the above code reliable? ANd how to redirect to another page like logout succesful after response.clear??

0

There are 0 best solutions below