ASP.NET MVC 5: Custom AuthorizeAttribute for custom authentication

In a previous post I wrote about how you can should protect your web app from human errors made by developers, by enforcing authentication by default.

Since adding the AuthorizeAttribute to every action involves global filters, we can use that to add our own custom authentication, by inheriting AuthorizeAttributeand overriding the AuthorizeCore and HandleUnauthorizeRequest methods.

We ‘ll start by adding a new .cs file (I also add a folder Attributes for all custom attributes) with the following code (read the comments for explanation):

And then you can just use it from your controller like this:

* You should also read “ASP.NET MVC 5: “Authorization” by default for your web app” to understand the commend //No Annotation, user must be logged in!