KatanaContrib Intro

With the latest release of ASP.NET MVC 5, project Katana also came out. The oauth authentication middlewares for some of the popular soc.networks and services like Google, Facebook, Twitter, Microsoft account were also delivered with Katana. Inspired by provided the authentication providers project KatanaContrib was born. Project KataContrib is created to be a community contribution for OWIN / Katana.

Note: KatanaContrib was designed to be modular, this means that all the middlewares or modules are separate dlls and are delivered as separate nuget packages.

The first release of KatanaContrib will include authentication middlewares for different 3rd party services/vendors. If you feel like or have something to contribute check out the trello board and ping a message to @KatanaContrib

TwitterGoogle+PinterestDeliciousDZoneSharing is caring

List of All Action Filters Provided in ASP.NET MVC 5

Thought it would be a good idea to have a list of all provided action filters that are available in MVC 5. Doing this because couldn’t find a resource in the web where all of them would be listed in one place. So here it is:

  • AuthorizeAttribute – represents a filter attribute that is used to restrict access by caller to an action method by validating if the user is authorized by indicated usernames or roles.
  • ChildActionOnlyAttribute - represents a filter attribute that is responsible  to indicate that the action method should be called only as a child action. A child action is an action that can only be invoked inside any view using Html.RenderAction()
  • HandleErrorAttribute - represents a filter attribute that is responsible and is used to handle an exception that is thrown by an action method.
  • OverrideActionFiltersAttribute - represents a filter attribute that overrides action filters defined at a higher level.
  • OverrideAuthenticationAttribute -  represents a filter attribute that is responsible and used to override authentication filters defined at a higher level.
  • OverrideAuthorizationAttribute - represents a filter attribute that is responsible and used to override authorization filters defined at a higher level.
  • OverrideExceptionFiltersAttribute – represents a filter attribute that is responsible and used to  overrides exception filters defined at a higher level.
  • OverrideResultFiltersAttribute - represents a filter attribute that is responsible and used to  overrides result filters defined at a higher level.
  • RequireHttpsAttribute - represents a filter attribute that is responsible and used to force the unsecured HTTP request to be resent over HTTPS.
  • ValidateAntiForgeryTokenAttribute – represents a filter that is responsible and used to prevent forgery of a request by validating an anti forgery token in the request.
  • ValidateInputAttribute – represents a filter that is responsible and used to mark the action method whose input must be validated.

Hope you find this list also useful.

Let me know if I have missed something.

ASP.NET MVC 5 Action Filter Types Overview

Filters in MVC are one of those feature which make ASP.NET MVC such a great framework out there! Filters are some of the best extension points provided in MVC.

With the latest release of MVC 5 new filters were added. In this post you will find an overview of all available filter types in MVC 5 and some notes how and when to use them.

What are action filters?

Action Filters are custom classes that provide pre-action and post-action behavior to the controllers action methods. This is a good thing because you may be in a situation when you need some logic to be performed before or after action execution.

Provided filter types in MVC 5

Override filter

Override filter is a new filter type that is used for indicating which filters need to be overridden. When creating a custom override filter you have to implement  implement IOverrideFilter as well to declare and implement  the  FiltersToOverride property. See below:

public class CustomOverrideFilter : FilterAttribute, IOverrideFilter
{
    public Type FiltersToOverride 
    {
        get
        {
            //This property is responsible for returning the filter that needs to be overridden.
            //For example:
            return typeof (IActionFilter);
        }
    }
}

You can read more regarding the new MVC 5 filter override in this post “How to use the ASP.NET MVC 5 Filter Overrides Feature

Authentication filter

New authentication filter makes security decisions if the action should be executed or not by validating the user authentication request. Also it is responsible for updating the Principle. This is also a new filter that was released with MVC 5. While creating a custom authentication filter you have to implement IAuthenticationFilter plus declare and implement the OnAuthentication and OnAuthenticationChallenge methods. See below:

public class CustomAuthenticatioFilter : FilterAttribute, IAuthenticationFilter    
{
    public void OnAuthentication(AuthenticationContext filterContext)
    {
        //This method is responsible for setting and modifying the principle for the current request though the filterContext .
        //Here you can modify the principle or applying some authentication logic.  
        //filterContext.Principal = ...;
    }
    public void OnAuthenticationChallenge(AuthenticationChallengeContext filterContext)
    {
        //This method is responsible for validating the current principal and permitting the execution of the current action/request.
        //Here you should validate if the current principle is valid / permitted to invoke the current action. (However I would place this logic to an authorization filter)
        //filterContext.Result = new RedirectToRouteResult("CustomErrorPage",null);
    }
}

More regarding the new authentication filter you can find in this post “Finally the new ASP.NET MVC 5 Authentication Filters!”.

Authorization filter

Authorization filter is also responsible for making security decisions if the action should be executed or not by validating whether the user is authorized by a given criteria or validating the requests properties. While creating a custom authorization filter you have to implement the IAuthorizationFilter, declare and implement OnAuthorization. See below:

public class CustomAuthorizationFilter : FilterAttribute, IAuthorizationFilter
{
    public void OnAuthorization(AuthorizationContext filterContext)
    {
        //This method is responsible for validating the user or properties (authentication/authorization ) and checking if he as authorization 
        //access to the action / controller or system (if the custom authorization filter is registered as a global filter)
        //The user can be validate by the role or some authorization criteria that needs to be applied.
    }
}
When to use:

Lets say that you have pages or actions in your web application that can be executed only by authorized user that have a specific role. This is a good fit to use the Authorize filter attribute and specify it Roles parameter.

Another reason touse it is when you have pages or actions that can be accessed only by authorized users that get redirected or linked by a specific URL. Here you have to create a custom authorization filter: validate if the user is authorized and check that the HttpContext.Request.UrlReferrer is a valid URL.

Action filter

Action filter is responsible for performing  additional logic before and after the controllers action execution. When creating a custom action filter you have to implement the IActionFilter, declare and implement OnActionExecuting and OnActionExecuted methods. See below:

public class CustomActionFilter : FilterAttribute, IActionFilter
{
    public void OnActionExecuting(ActionExecutingContext filterContext)
    {
        //This method gets invoked before action execution.
        //Here you can perform different operation from validating properties, adding additional properties to the context,
        //perform some additional operation even do a redirect if needed and so on.
        //In general here you will have logic that needs to be performed before action execution
    }
    public void OnActionExecuted(ActionExecutedContext filterContext)
    {
        //This method get invoked after action execution.
        //Here you can perform the same things as in the OnActionExecuting method,
        //the only different is that here you will be placing logic that needs to be performed before action execution.
        //Note: the filterContext.Canceled is TRUE if you change the Result to another in the OnActionExecuting method. 
        filterContext.Canceled == true;
    }
}
When to use:

Action filter is really a great thing because during the OnActionExecuting the  filterContext parameter, that passed to the method, has a lot of information about the current context. You can use this information to perform logic or you can manipulate and change the context according to your logic needs.

Action filters can be used to audit and log user activities on a set of actions or controllers or the whole application.

Result filter

Result filter is responsible for performing additional logic before and after action result execution. To create a custom result filter you’ll have to implement IResultFilter, declare and implement OnResultExecuting and OnResultExecuted. See below:

public class CustomResultFilter : FilterAttribute, IResultFilter
{
    public void OnResultExecuting(ResultExecutingContext filterContext)
    {
        //This method gets invoked before the ActionResult is executed.
        //Here you can perform different operations like validate the action result that will be returned to the user,
        //replace the action result, add additional extra metadata to the HTTP context,
        //Note: You can cancel ActionResult execution by setting by setting
        filterContext.Cancel = true;
    }
    public void OnResultExecuted(ResultExecutedContext filterContext)
    {
        //This method gets invoked after the Action is executed.
        //Here you can't update or change action result because it has already been executed.
        //However you can still write to the Http response / context.
        //Note: Indicated that the ActionResult execution was canceled (the cancelation can be done in OnResultExecuting):
        filterContext.Canceled;
    }
}
When to use:

One good example that comes into mind is changing the model that is being returned to a view model using AutoMapper or other mapping lib that you prefer. Another example is changing the result if we have an invalid model or an invalid result to redirect to an error page. And more…

Exception filter

Exception filter is responsible for handling errors that are raised by the action or action results. To create a custom exception handler you have to implement the IExceptionFilter interface, declare and implement its OnException method. See below:

public class CustomException : FilterAttribute, IExceptionFilter
{
    public void OnException(ExceptionContext filterContext)
    {
        //This method gets invoked after all other filter have been executed and if an exception occurred during method execution.
        //Here you should place logic to handle the exception the way you need. 
    }
}
When to use:

Use this filter to log the exception or to redirect to another action. You may handle the exception in your application the way you need.


That’s it!

We have covered all available filter types that are provided in MVC 5 and now have a glance look how to create a custom filter of each type.

Hope you found this post useful! If you have something to add or share, you are appreciated to do so in the comments.

How to use the ASP.NET MVC 5 Filter Overrides Feature

In the previous post we took a look at the new authentication filter and its strong points. There is one more new filter that has been released with MVC 5 that was requested by many developers out their over a long time. This is the new filter override feature! In the previous versions of MVC, there was no way to override a filter for just a single action or controller. What you had to do is to apply the filter for each and every action and controller one by one and this was a huge waste of development time. Instead of doing this developers found ways to implement filter overrides using workaround (been there…). But usually the usage of workarounds lead to the lack of code consistency. So as a solution for this, Filter Overrides feature was introduced in MVC 5.

Important Note:

There is a well-known bug associated with MVC 5 Filter Overrides feature. It has been recorded in MVC 5 RC and has been fixed in MVC 5.1. However there is a simple workaround for this bug.

Filter Overrides in action

Imagine a situation where you want to exclude a globally applied authorization filter just only for a single action method. This was something you could not implement easily with the previous versions of MVC. But now the MVC 5 Filter Overrides feature provides you this capability with few lines of code. Lets have a look at the following code snippet:

[Authorize(Users = "Admin")]
public class HomeController : Controller
{
    public ActionResult Index()
    {
        return View();
    }

    public ActionResult About()
    {
        ViewBag.Message = "Your application description page.";
        return View();
    }

    public ActionResult Contact()
    {
        ViewBag.Message = "Your contact page.";
        return View();
    }
}

As you can see AuthorizeAttribute has been decorated to the HomeController class with the user ‘Admin’. So it applies to all the actions inside the controller. Assume you want to bypass this filter just for the ‘About’ action. You want to provide access to ‘About’ page just for user ‘Dan’ only. In MVC 5 you can achieve this by adding two lines of code as illustrated in the following code snippet.

[Authorize(Users = "Admin")]
public class HomeController : Controller
{
    public ActionResult Index()
    {
        return View();
    }

    [OverrideAuthorization]
    [Authorize(Users = "Dan")]
    public ActionResult About()
    {
        ViewBag.Message = "Your application description page.";
        return View();
    }

    public ActionResult Contact()
    {
        ViewBag.Message = "Your contact page.";
        return View();
    }
}

OK. That’s it. Now all the actions inside the Home Controller can only be accessed by ‘Admin’ except the ‘About’ action. The ‘About’ action is only available for ‘Dan’. So now you can get rid of the headache of applying filters for each and every action where you need to exclude just one or two actions.

There are 5 types of override filters available for each of filter types:

  1. OverrideActionFilters
  2. OverrideAuthentication
  3. OverrideAuthorization
  4. OverrideExceptionFilters
  5. OverrideResultFilters

You can use the relevant override filters wherever is needed.

Insight to the Filter Overrides Bug

As I mentioned earlier, there is a well-known bug associated with Filter Overrides feature in MVC 5 RC and MVC 5 RTM. It has been identified and tracked by the ASP.NET team in HERE.

However this bug is fixed in MVC 5.1 preview. But at the time of this writing, MVC 5.1 is not released officially. But still you can download the latest MVC source code  and take a look how it was resolved.

The developers who are using the MVC 5 RC or MVC 5 RTM can still use the Filter Override feature by implementing a simple workaround.

Filter Override Bug Workaround

For creating a bug workaround you will have to do a couple of things:

Implement a custom class that will inherit from the action filter that you want to override and implement the IOverrideFilter. You’ll have to implement the FiltersToOverride property where you have to identify the filters that you want to override. For instance lets create a simple workaround for the example that has been described above:

public class MyOverrideAuthorizeAttribute : AuthorizeAttribute, IOverrideFilter
{
    public Type FiltersToOverride
    {
        get
        {
            return typeof(IAuthorizationFilter);
        }
    }
}

And now the controller implementation will change to:

[Authorize(Users = "Admin")]
public class HomeController : Controller
{
    public ActionResult Index()
    {
        return View();
    }

    [MyOverrideAuthorize(Users = "Dan")]
    public ActionResult About()
    {
        ViewBag.Message = "Your application description page.";
        return View();
    }

    public ActionResult Contact()
    {
        ViewBag.Message = "Your contact page.";
        return View();
    }
}

Simple as that!

Filter override feature is a great thing that was released with MVC 5! Despite there is a bug and it can’t be used the way it was designed, still there is an easy workaround. Rather than that this is an excellent feature that a lot of developers were waiting for!  No doubts, it can be a big life saver!

Finally the new ASP.NET MVC 5 Authentication Filters!

If you have been working with previous versions of ASP.NET MVC you may probably remember those times when you had to place your authentication logic into a custom authentication filter and this wasn’t good because some authorization logic was also added to the same custom filter. Or when you had to set the principal to your custom one you had to do this in the global.asax file in the Application_AuthenticateRequest as described bellow.

protected void Application_AuthenticateRequest(object sender, EventArgs e)
{
    if (Request.IsAuthenticated)
    {
       // Change the default authenticated user principal to our custom object. The object may contain application specific such as "any user's metadata that you require" .
        OverwriteUserDefaultPrincipalWithCustomPrincipal(HttpContext.Current);
    }
 } 

Such things were usually done because of the MVC application pipeline. You need it to get executed before the authorization filter. Placement of principle overwriting code in an authorization filter can lead to bugs, if  new authorization filters for validating some extra validation on the principle are added. You won’t be always able to manage the execution order of filters and this will lead to bugs where you’ll have the default principle set in the context.

If you have been?! You should know that now those days are over!!!

Visual studion 2013 is out and with it is MVC5. It came out with some great new features and one of these features is the new authentication filter. Here is a short overview on how to implement your custom action filter.

public class CustomAuthenticatioFilter : ActionFilterAttribute, IAuthenticationFilter
{
    public void OnAuthentication(AuthenticationContext filterContext)
    {
        //This method is responsible for setting and modifying the principle for the current request though the filterContext .
        //Here you can modify the principle or applying some authentication logic.  
        //filterContext.Principal = ...;
    }

    public void OnAuthenticationChallenge(AuthenticationChallengeContext filterContext)
    {
        //This method is responsible for validating the current principal and permitting the execution of the current action/request.
        //Here you should validate if the current principle is valid / permitted to invoke the current action. (However I would place this logic to an authorization filter)
        //filterContext.Result = new RedirectToRouteResult("CustomErrorPage",null);
    }
}

You should remember that the authentication and authorization filters differ:

  1. Authentication filters execute before the authorization ones.
  2. Authentication filters are for setting or updating the principle for the current request.
  3. Authorization filters are for verifying if the current user has permissions to execute the current request.

In the current modern web the greatest value of authentication filters comes when you need to allow your users to sign in to the system using third-party vendors accounts such like twitter, github, linkedin, dropbox or other vendors that support oauth or openid.

Okay lets sum up here! The authentication filters is a great feature that I and many other developers out there are glad to see and were waiting for.  It works great  for implementing authentication to third party vendors, setting you custom principal and moving the authentication logic from the authorization filter what makes the code more clean and declarative.

So this is one of the reasons why start updating to MVC 5!

Back to top