Asp.net-Mvc

在身份 2.0 中重定向未經授權的使用者

  • November 30, 2016

對於我的 mvc5 項目,我已經實現了預設身份,但根據要求對其進行了更改。現在我想將未經授權的使用者重定向到我創建的視圖。我創建了一個自定義授權過濾器。當未經授權的使用者進入時,它會出現在我的錯誤視圖中。我可以通過 URL 辨識它。但問題是它沒有在視圖中顯示內容。相反,它顯示 HTTP 404 錯誤。我把我的程式碼放在下面。我知道這已經在這裡被問過好幾次了。但我仍然無法解決它。所有幫助表示讚賞。提前致謝!

public class CustomAuthorize : AuthorizeAttribute
{
   protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
   {
       if (!filterContext.HttpContext.User.Identity.IsAuthenticated)
       {
           base.HandleUnauthorizedRequest(filterContext);
       }
       else
       {
           filterContext.Result = new RedirectToRouteResult(new
           RouteValueDictionary(new { controller = "Error", action = "AccessDenied" }));
       }
   }
}

錯誤控制器

public class ErrorController : Controller
{
   // GET: Error
   public ActionResult Index()
   {
       return View();
   }

   public ActionResult AccessDenied()
   {
       return View();
   }
}

拒絕訪問視圖

<h2>AccessDenied</h2>

Access Denied

在特定控制器上

[CustomAuthorize(Roles = "Admin")]
public class ProductTypeController : Controller
{
}

我得到錯誤

HTTP 404。您正在查找的資源(或其依賴項之一)可能已被刪除、名稱已更改或暫時不可用。請查看以下 URL 並確保其拼寫正確。

更新的問題

現在我想將未經授權的使用者重定向到 ErrorView 並將未經身份驗證的使用者重定向到登錄頁面。我已將修改後的 CustomAuthorise 放在下面。但它不起作用。請指導我..

public class CustomAuthorize : AuthorizeAttribute
{
   protected override bool AuthorizeCore(HttpContextBase httpContext)
   {
       if (!httpContext.Request.IsAuthenticated)
           return false;
       else 
           return true;
   }
   protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
   {
       filterContext.Result = new RedirectToRouteResult(new
       RouteValueDictionary(new { controller = "Error", action = "AccessDenied" }));
   }
} 

對於重定向未經授權的使用者,您不需要自定義AuthorizeAttribute. 只需在Startup.ConfigureAuth(IAppBuilder app)方法或您自定義的 OWIN 啟動方法中添加以下行:

public void ConfigureAuth(IAppBuilder app)
{
   app.UseCookieAuthentication(new CookieAuthenticationOptions
   {
       AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
       LoginPath = new PathString("/Error/AccessDenied"),
   });
}

但是,如果您想區分未經身份驗證的使用者和未經授權的使用者。像這樣編寫您的自定義過濾器:

public class MyAuthAttribute: AuthorizeAttribute
{
   protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
   {
       if(filterContext.HttpContext.User.Identity.IsAuthenticated)
       {
           filterContext.Result = new RedirectResult("/Error/AccessDenied");
       }
       else
       {
           base.HandleUnauthorizedRequest(filterContext);
       }        
   }
}

然後你可以在 OWIN 啟動方法中添加登錄 url:

LoginPath = new PathString("/Account/Login")

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