Force Sign in as a different user while using Windows Authentication in asp.net

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

namespace WindwsAuthTest.Controllers {
   public class HomeController : Controller {
      public ActionResult Index() {
         ViewBag.Message = "Welcome to ASP.NET MVC!";
         return View();
      }

      public ActionResult About() {
         return View();
      }

      public ActionResult Logout() {
         return View();
      }

      public ActionResult SignInAsDifferentUser() {

         HttpCookie cookie = base.Request.Cookies["TSWA-Last-User"];

         if (base.User.Identity.IsAuthenticated == false || cookie == null || StringComparer.OrdinalIgnoreCase.Equals(base.User.Identity.Name, cookie.Value)) {

            string name = string.Empty;
            if (base.Request.IsAuthenticated) {
               name = this.User.Identity.Name;
            }

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

            base.Response.AppendHeader("Connection", "close");
            base.Response.StatusCode = 0x191;
            base.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
            base.Response.Write("PageResources.UnauthorizedAccessMessage");
            base.Response.End();
            return RedirectToAction("Index");
         }

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

         return RedirectToAction("Index");
      }
   }
}

Advertisement

6 thoughts on “Force Sign in as a different user while using Windows Authentication in asp.net”

  1. In my case I just want to Logout (not login with different user). So how can I implement this.

    Let me know if you have any solution for MVC. I am using Windows Authentication for login.

    Reply
    • The same question like me.
      I just create a button linked to that action and do not type user information, and the same result as log out.
      I'm using MVC5.

      Reply

Leave a Comment