Equivalent to IAuthenticationFilter in MVC6

I am moving the Web Api 2 project to MVC 6 because Microsoft integrates the two APIs in ASP.NET 5. In my WebApi project, I had a custom attribute filter class that could authenticate, allow, and prevent transaction retries using a combination of public key, secret HMAC key and authentication (basically with this with some settings to fit into my project).

Now in MVC6, as I understand it, I have to stop using anything in the Microsoft.Web.Http namespace and use Microsoft.AspNet.Mvc instead. So I did this, but Microsoft.AspNet.Mvc.Filters does not have a similar equivalent to Web Api 2 IAuthenticationFilter .

This is a problem for me, because my AuthenticationFilter client implemented all the IAuthenticationFilter with all the logic there. More importantly, he used the context to temporarily store the account public key, so my controller could access it to download the account in turn.

So my question is how to filter requests in MVC6 correctly using a filter class like authentication to intercept requests and return the appropriate status codes? I cannot find any article specifically dedicated to these details (they all tend to cover MVC5).

+6
source share
2 answers

I know this is an older question, but hopefully someone (maybe even myself) can find the value in the answer.

MVC6 really has an alternative. You have

 public abstract class AuthorizationFilterAttribute : Attribute, IAsyncAuthorizationFilter, IAuthorizationFilter, IOrderedFilter 

which basically tells you that you can create your own class, infer it from it (the namespace of all these interfaces, btw, is equal to Microsoft.AspNet.Mvc.Filters , and that should be it). You can either decorate this action, or you can do it in Startup.cs to apply to all actions:

  public void ConfigureServices(IServiceCollection services) { // Add MVC services to the services container. services.AddMvc(options => { // add an instance of the filter, like we used to do it options.Filters.Add(new MySpecialFilter()); }); services.AddTransient<LogFilter>(); } 

If you want to use a little more logical in the filter (for example, my LogFilter above), which is created through DI, you need to use the Service Filters or type filters .

Now you can decorate actions with [ServiceFilter(typeof(LogFilter))] or use o.Filters.Add(new ServiceFilterAttribute(typeof(LogFilter))); in the file Startup.cs. But keep in mind, for this you need to register a type with a DI container , as I did above with a call to .AddTransient<>() .

+4
source

The IAuthenticationFilter is no longer there, and the IAuthorizationFilter just doesn't replace it in MVC 6

Reason: authentication is IMPOSSIBLE for authorization.

Therefore, the IMO authentication filter must remain in stock!

+1
source

All Articles