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