2013-04-08 103 views
3

我正在瀏覽ASP.NET MVC中的Controller類,並發現它實現了IAuthenticationFilter接口。然而,我無法理解如何在我的控制器中實現OnAuthentication()和OnAuthenticationChallenge()方法,以及何時調用這些方法。在asp.net中的IAuthenticationFilter接口實現MVC

如果有人能向我解釋或與我分享任何解釋這一點的鏈接,這將是非常有益的。即使我在MSDN上無法找到任何資源。

+1

你不會找到任何文件,因爲提到'IAuthenticationFilter'接口加入到ASP.NET MVC兩個星期前(3月22日):http://aspnetwebstack.codeplex.com/SourceControl/ changeset/178ec82f90f056f958994903fe0998d3e127a0cb – nemesv 2013-04-08 11:16:12

+0

@nemesv - 哦,是的,謝謝你的回覆,我的錯誤。 – Bibhu 2013-04-08 11:24:31

回答

2

您可以使用臨時更改HttpContext.User具有自己的值的Iprincipal後代對象。只需要通過AuthenticationContext傳遞一個新的IPrincipal。我認爲,代表另一個用戶(暫時)採取行動將是有益的。例如:何時替換某人休假,還是開發階段。所以,你可以在VS2013預覽MVC 5項目中使用。

例如在控制器(如IAuthenticationFilter):

protected override void OnAuthentication(System.Web.Mvc.Filters.AuthenticationContext filterContext) 
{ 

//fill userPrincipal… 

    filterContext.Principal = new RolePrincipal(userPrincipal); 

    //Or pass an ActionResult, if you want 

    filterContext.Result = new RedirectResult("http://www.stackoverflow.com"); 

} 
6

使用OnAuthentication用於設置或修改當前請求的主體。

使用OnAuthenticationChallenge驗證當前主體並允許執行當前請求。例如:

public class CustomAuthenticatioFilter : ActionFilterAttribute, IAuthenticationFilter 
{ 
    public void OnAuthentication(AuthenticationContext filterContext) 
    { 
     //Here you are setting current principal 
     filterContext.Principal = new ClaimsPrincipal(); 
    } 

    public void OnAuthenticationChallenge(AuthenticationChallengeContext filterContext) 
    { 
     //Here you're checking current action and redirecting to ErrorPage 
     filterContext.Result = new RedirectToRouteResult("ErrorPage",null); 
    } 
} 
+1

如果只有IAuthenticationFilter的MSDN文檔包含前兩個句子! – 2014-03-06 13:37:04