很多情況下目標Action方法都要求在一個安全上下文中被執行,這里所謂的安全上下文主要指的是當前請求者是一個經過授權的用戶。授權的本質就是讓用戶在他許可的權限范圍內做他能夠做的事情,授權的前提是請求者是一個經過認證的用戶。質詢-應答(Chanllenge-Response)”是用戶認證采用的一種常用的形式,認證方向被認證方發出質詢以要求其提供用于實施認證的用戶憑證,而被認證方提供相應的憑證以作為對質詢的應答。旨在目標Action方法執行之前實施身分認證的AuthenticationFilter也對這種認證方法提供了支持。
所有的AuthenticationFilter類型均實現了IAuthenticationFilter接口,該接口定義在命名空間“System.Web.Mvc.Filters”下(其他四種過濾器接口都定義在“System.Web.Mvc”命名空間下)。如下面的代碼片斷所示,OnAuthentication和OnAuthenticationChallenge這兩個方法被定義在此接口中,前者用于對請求實施認證,后者則負責將相應的認證質詢發送給請求者。
1: public interface IAuthenticationFilter
2: { 3: void OnAuthentication(AuthenticationContext filterContext);
4: void OnAuthenticationChallenge(AuthenticationChallengeContext filterContext);
5: }
定義在IAuthenticationFilter接口的兩個方法都將一個上下文對象作為其唯一參數。OnAuthentication方法的這個參數類型為AuthenticationContext,如下面的代碼片斷所示,它是ControllerContext的子類。AuthenticationContext的ActionDescriptor返回的自然是用于描述目標Action方法的ActionDescriptor對象。借助于PRincipal屬性,我們可以獲取或設置代表當前用戶的Principal對象。如果我們在執行OnAuthentication方法的過程中設置了AuthenticationContext的Result屬性,提供的ActionResult將直接用于響應當前請求。
1: public class ActionExecutingContext : ControllerContext
2: { 3: public ActionExecutingContext();
4: public ActionExecutingContext(ControllerContext controllerContext, ActionDescriptor actionDescriptor,IDictionary<string, object> actionParameters);
5:
6: public virtual ActionDescriptor ActionDescriptor { get; set; } 7: public virtual IDictionary<string, object> ActionParameters { get; set; } 8: public ActionResult Result { get; set; } 9: }
OnAuthenticationChallenge方法的參數類型為AuthenticationChallengeContext。如下面的代碼片斷所示,它依然是ControllerContext的子類。它同樣具有一個用于描述目標Action方法的ActionDescriptor屬性,其Result屬性代表的ActionResult對象將用于響應當前請求。
1: public class ActionExecutedContext :
新聞熱點
疑難解答