Thursday, 1 August 2013

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");
      }
   }
}

Advertisements
Advertisements

8 comments:

  1. This comment has been removed by the author.

    ReplyDelete
  2. I did use the code from http://signinas.codeplex.com/ which worked perfectly for my project.

    ReplyDelete
  3. This is cool and simple for MVC, also works in MVC 5, good work

    ReplyDelete
  4. Thank you . This is perfectly working.

    ReplyDelete
  5. not work for Chrome

    ReplyDelete
  6. Thanks, this work perfectly. To redirect, i used a script tag with window.location='/xx' to redirect, inside Response.Write().

    ReplyDelete
  7. 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.

    ReplyDelete
    Replies
    1. 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.

      Delete