I have an intranet project written in MVC 4 which uses Windows Authentication to authorise and authenticate users.
I need to add a 'Login as another user' functionality.
After some searching I found this solution which suggests returning a 401, and created the following Action (which is called using a form):
//
// POST: /Home/LogOut
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult LogOut()
{
return new HttpUnauthorizedResult();
}
The Action gets called, and the browser pops up a username and password window, however as the result redirects back to the Action, a 401 is always returned.
How do I redirect the user back to the previous action, once they have logged in with the new credentials?
Is there a way to invalidate the credentials on the server side instead of just returning a 401?
Enabling Windows Authentication First, while developing an MVC application, you use the ASP.NET Development Web Server included with Visual Studio. By default, the ASP.NET Development Web Server executes all pages in the context of the current Windows account (whatever account you used to log into Windows).
Start Visual Studio and select Create a new project. In the Create a new project dialog, select ASP.NET Core Web App (or Web API) > Next. In the Configure your new project dialog, enter Project name > Next. In the Additional Information dialog, select Authentication Type as Windows.
People reverse engineered\decompiled some code from Sharepoint that happens to have this feature.
I tested it in an ASP.NET MVC 5
app and it's working as expected.
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 = 401; // Unauthorized;
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");
}
Source:
Force Sign in as a different user while using Windows Authentication in asp.net
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With