Dot-Net

帶有 ADFS 聲明的 .Net MVC 授權屬性的重定向循環

  • December 20, 2018

我在使用 .Net MVC 5 應用程序配置 ADFS 時遇到問題。

我已經在 VS 2015 中將我的項目配置為使用聲明,它工作正常,但我有一個問題。

我可以登錄,使用 ADFS,我可以檢查使用者角色等。當我嘗試使用時出現問題

[Authorize(Roles="somenonExistingRole")]

儘管我已經通過身份驗證,但當再次進行身份驗證時,我被重定向到 ADFS 頁面,並且我被重定向到發生循環的頁面。頁面將我發送到 ADFS 門戶,ADFS 將我重定向到門戶,經過幾次嘗試後,我從 ADFS 收到錯誤(對許多請求)

我必須自己實現角色提供者之類的東西嗎?或者我需要配置一些額外的東西。也許我可以限制嘗試次數?為什麼我已經準備好角色後會重定向到 ADFS?

根據要求,程式碼中實際上沒有太多可顯示的內容:我正在測試的控制器:

public class HomeController : Controller
   {
       public ActionResult Index()
       {
           return View();
       }
       [Authorize]
       public ActionResult About()
       {
           var u = HttpContext.User;


           if (u.IsInRole("/"))
           {
               ViewBag.Message = "User is in role.";
           }
           else
           {
               ViewBag.Message = "User is NOT in role.";
           }

           return View();
       }
       [Authorize(Roles = "/nonexistingRole")]
       public ActionResult Contact()
       {

           ViewBag.Message = "Your contact page.";

           return View();
       }
   }

和配置身份驗證部分

public void ConfigureAuth(IAppBuilder app)
{
   app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);

   app.UseCookieAuthentication(new CookieAuthenticationOptions());

   app.UseWsFederationAuthentication(
       new WsFederationAuthenticationOptions
       {
           Wtrealm = realm,
           MetadataAddress = adfsMetadata, 

       });
}

要解決循環問題,您應該覆蓋AuthorizeAttribute.

預設情況下,當使用者的角色不符合AuthorizeAttribute要求時,MVC 會返回 401 Unauthorized。這會初始化對身份提供者的重新認證請求。由於使用者已經登錄,AAD 返回到同一頁面,然後發出另一個 401,創建重定向循環。在這裡,我們重寫了 AuthorizeAttribute 的 HandleUnauthorizedRequest 方法,以顯示在我們的應用程序上下文中有意義的內容。

此類是在使用 VS 2015 創建新的 MVC 項目時生成的:

[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = true, AllowMultiple = true)]
public class AuthorizeAttribute : System.Web.Mvc.AuthorizeAttribute
{        
   protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
   {
       if (filterContext.HttpContext.Request.IsAuthenticated)
       {
           //One Strategy:
           //filterContext.Result = new System.Web.Mvc.HttpStatusCodeResult((int)System.Net.HttpStatusCode.Forbidden);

           //Another Strategy:
           filterContext.Result = new RedirectToRouteResult(
               new RouteValueDictionary(
                   new
                   {
                       controller = "Error",
                       action = "ShowError",
                       errorMessage = "You do not have sufficient priviliges to view this page."
                   })
               );
       }
       else
       {
           base.HandleUnauthorizedRequest(filterContext);
       }
   }
}

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