Asp.net-Mvc

‘以其他使用者身份登錄’ MVC 4 Windows 身份驗證

  • March 21, 2018

我有一個用 MVC 4 編寫的 Intranet 項目,它使用 Windows 身份驗證來授權和驗證使用者。

我需要添加“以其他使用者身份登錄”功能。

經過一番搜尋,我找到了這個建議返回 401 的解決方案,並創建了以下操作(使用表單呼叫):

   // 
   // POST: /Home/LogOut

   [HttpPost]
   [ValidateAntiForgeryToken]
   public ActionResult LogOut()
   {
       return new HttpUnauthorizedResult();
   }

Action 被呼叫,瀏覽器彈出使用者名和密碼視窗,但是當結果重定向回 Action 時,總是返回 401。

使用新憑據登錄後,如何將使用者重定向回上一個操作?

有沒有辦法使伺服器端的憑據無效,而不僅僅是返回 401?

人們從 Sharepoint逆向工程\反編譯了一些恰好具有此功能的程式碼。

我在一個ASP.NET MVC 5應用程序中對其進行了測試,它按預期工作。

該程式碼基於反編譯具有“以不同使用者身份登錄”功能的 Microsoft.TeamFoundation.WebAccess。

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

}

來源:

在 asp.net 中使用 Windows 身份驗證時強制以其他使用者身份登錄

引用自:https://stackoverflow.com/questions/17871816