2

我有一個通常使用基本身份驗證的MVC應用程序。這使我們可以將應用程序用戶更改爲不同的Active Directory用戶,以實現可選的管理功能。我們通過設置response.StausCode = 401這樣做: -ASP.NET MVC 401 - Unathorized不提示登錄

Response.Clear(); 
Response.StatusCode = (Int32)HttpStatusCode.Unauthorized; 
Response.AddHeader("WWW-Authenticate", "Realm=Secured Site"); 
Response.AddHeader("Refresh", "0;"); 
Response.End(); 

也能正常工作,但現在我想在應用程序中使用Windows身份驗證,但仍允許用戶使用以前的方法來改變。這又似乎起初應用程序加載時(即導航到站點選擇'changeuser'actionlink)工作。問題是,一旦你從索引頁導航離開'更改用戶'actionlink不會提示用戶再次登錄,即使401已經設置。

任何指導讚賞。

+0

我敢肯定的是,用戶代理緩存請求之間的基本HTTP憑證 - 所以當它得到它只是發回緩存的憑據,用戶之前輸入的401 - 它發送憑據爲每個請求反正。 –

+0

With Basic我每次設置statuscode = 401時都會得到一個登錄窗口,這是我想用Windows驗證發生的事情,如果位置 – Parsley

回答

0

令人驚訝的是,似乎瀏覽器不支持這一點。我發現一個朋友這個問題,問類似的事情,去年六月:

Logging a user out when using HTTP Basic authentication

他鏈接到另一個問題,最好的答案是有點傻:

How to log out user from web site using BASIC authentication?

基本身份驗證並非旨在管理退出。你可以做到,但不能完全自動。

你需要做的是讓用戶點擊一個註銷鏈接,併發送一個'401 Unauthorized'作爲迴應,使用相同的領域,並在與你發送請求登錄的普通401相同的URL文件夾級別。

接下來他們必須被定向輸入錯誤的證書,例如。一個空白的用戶名和密碼,作爲響應,您發回「您已成功註銷」頁面。然後,錯誤/空白憑證將覆蓋先前正確的憑證。

+0

謝謝Danny的幫助。我有'基本身份驗證'工作非常符合我的需要,問題出現在'Windows身份驗證',我將StatusCode設置爲401,但登錄框不出現 – Parsley

+0

我相信這是同樣的事情 - 瀏覽器已緩存基本身份驗證,所以當它看到401頭時,它只是再次發送基本身份驗證信息:-( –

1

你可以這樣做,但它確實需要一些欺騙。該代碼基於反編譯Microsoft.TeamFoundation.WebAccess,其中包含「以其他用戶身份登錄」功能,並重構爲使用MVC。

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