Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Authentication filters in MVC 5

Authentication filters from Release Notes page

Authentication filters are a new kind of filter in ASP.NET MVC that run prior to authorization filters in the ASP.NET MVC pipeline and allow you to specify authentication logic per-action, per-controller, or globally for all controllers. Authentication filters process credentials in the request and provide a corresponding principal. Authentication filters can also add authentication challenges in response to unauthorized requests.

Can some one provide the practical use of this? Where I can use this AuthenticationFilters exactly?

Earlier I use to manage Access Control List for a action/controller by writing own CustomAttribute: FilterAttribute, IAuthorizationFilter and implement public void OnAuthorization(AuthorizationContext filterContext) . Is it possible to use this AuthenticationFilter here?

like image 955
Murali Murugesan Avatar asked Sep 27 '13 10:09

Murali Murugesan


1 Answers

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

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.

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.

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.

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

  • 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

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.

like image 142
Wiktor Zychla Avatar answered Oct 11 '22 22:10

Wiktor Zychla