Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extend AuthorizeAttribute Override AuthorizeCore or OnAuthorization

Using ASP.NET MVC I am creating a custom Authorize attribute to take care of some custom authorization logic. I have looked at a lot of examples and it is pretty straight forward but my question is which method is best to override, AuthorizeCore or OnAuthorization? I have seen many examples overriding one or the other. Is there a difference?

like image 201
Nick Olsen Avatar asked Jul 28 '11 14:07

Nick Olsen


People also ask

How do I override an authorized attribute in .NET core?

Right-click on the solution and add a new class. Enter the class name and click on Add. Next Inherite Attribute, IAuthorizationFilter to CustomAuthorization class which has overridden the OnAuthorization method. The OnAuthorization Method has the AuthorizationFilterContext parameter.


2 Answers

The clue is in the return types:

AuthorizeCore returns a boolean - it is decision making code. This should be limited to looking at the user's identity and testing which roles they are in etc. etc. Basically it should answer the question:

Do I want this user to proceed?

It should not perform any additional activities "on the side".

OnAuthorize returns void - this is where you put any functionality that needs to occur at this point. e.g. Write to a log, store some data in session etc etc.

like image 196
BonyT Avatar answered Oct 30 '22 10:10

BonyT


You should put any code that must run regardless of whether the user is being authorized for the first time, or if they are using a cached authorization in AuthorizeCore.

If you look at the source code, you can see that AuthorizeCore gets called by both OnAuthorize and OnCacheAuthorization. This allows the authorization to be cached but still allow certain actions and to make the actual decisions about the authorization.

If you need something from the AuthorizationContext then you can create a property to hold the information and then access that in the AuthorizeCore method.

like image 17
Erik Funkenbusch Avatar answered Oct 30 '22 10:10

Erik Funkenbusch