ASP.NET MVC 5: Custom AuthorizeAttribute for custom authentication

0 0 votes
Article Rating

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

In this, lets check how to write your very own custom AuthorizeAttribute!

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!

0 0 votes
Article Rating
Subscribe
Notify of
guest
9 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments

[…] i prefer the AuthorizeAttribute solution, there is an other simpler way with a base Controller and […]

Byron

Perfect, this was very helpful.

Umair Anwaar

Hellow brother this is perfect view but i have a problem I am not able to pass the ResorceKey and the OperationKey every time i am getting empty on each action.

[…] i prefer the AuthorizeAttribute solution, there is an other simpler way with a base Controller and […]

Anatolii Grynchuk

Where did you take the protected override bool AuthorizeCore(HttpContextBase httpContext)

Will Strege

Where does “myMembership” come from?