Bibhu
Bibhu

Reputation: 4091

IAuthenticationFilter interface implementation in asp.net MVC

I was going through the Controller class in ASP.NET MVC, and found out that it implements IAuthenticationFilter interface. However I am unable to understand how can I implement, its methods OnAuthentication() and OnAuthenticationChallenge(), in my controller and when these will be called.

It will be very helpful if someone can explain it to me or share with me any link that explains this. Even I was unable to find any resource on this in MSDN.

Upvotes: 3

Views: 6000

Answers (2)

Oleksii Aza
Oleksii Aza

Reputation: 5398

Use OnAuthentication for setting or modifying the principal for the current request.

Use OnAuthenticationChallenge for validating current principal and permitting the execution of current request. For example:

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

Upvotes: 7

Kornel Regius
Kornel Regius

Reputation: 81

You can use for temporarly change HttpContext.User Iprincipal descendant object with own value. Only need to pass a new IPrincipal by AuthenticationContext. I think, it's will be usefull for to act on behalf of another user (temporarly). For example: when to replace someone for holiday, or in developer phase. So, you can use in VS2013 preview MVC 5 project.

For example in your controller (as 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");

}

Upvotes: 2

Related Questions