Rectangle 27 0

c Authentication filters in MVC 5?


  • authentication is for estabilishing a principal for current request
  • authorization is to verify whether or not the current principal is permitted to execute current request

An example use is changing the authentication for just few selected controllers. Suppose for example that your whole site uses Forms Authentication where principals are taken from forms cookies.

As the docs says, the custom authentication filter provides an authentication per-action, per-controller or globally.

However, you have a selected controller that acts as OAuth2 Resource Server where requests come from Service Providers (servers) and there are no forms cookies, rather, an OAuth2 access token is provided by the service provider server.

The reason to introduce authentication filters is to separate authentication from authorization, where:

This is where a custom authentication filter comes into play - its task is to translate the token to a principal for the lifetime of current request only, just for the only controller that acts as the resource server endpoint. You don't want the whole site to accept OAuth2 tokens, rather the one particular controller.

This was not clearly separated before authentication filters were introduced. Personally, I used to use authorization filters for this, however having two separate layers of filters in this particular order (authentication first, then authorization) is just cleaner.

Note