Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Asp.net Core WebAPI Resource based authorization outside controller level

I'm creating a Web API with users having different roles, in addition as any other application I do not want User A to access User B's resources. Like below:

Orders/1 (User A)

Orders/2 (User B)

Of course I can grab the JWT from the request and query the database to check if this user owns that order but that will make my controller Actions' too heavy.

This example uses AuthorizeAttribute but it seems too broad and I'll have to add tons of conditionals for all routes in the API to check which route is being accessed and then query the database making several joins that lead back to the users table to return if the request Is Valid or not.

Update

For Routes the first line of defense is a security policy which require certain claims.

My question is about the second line of defense that is responsible to make sure users only access their data/resources.

Are there any standard approaches to be taken in this scenario ?

like image 544
Mozart AlKhateeb Avatar asked Apr 16 '20 20:04

Mozart AlKhateeb


People also ask

How do I bypass authorization in Web API?

If you want to allow anonymous access you can use the [AllowAnonymous] attribute. This will block access to all methods when a user is not authorized, except the GetData() method which can be called anonymously.

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.

How do I Authorize ASP.NET Web API?

Web API provides a built-in authorization filter, AuthorizeAttribute. This filter checks whether the user is authenticated. If not, it returns HTTP status code 401 (Unauthorized), without invoking the action. You can apply the filter globally, at the controller level, or at the level of individual actions.


1 Answers

Using [Authorize] attribute is called declarative authorization. But it is executed before the controller or action is executed. When you need a resource-based authorization and document has an author property, you must load the document from storage before authorization evaluation. It's called imperative authorization.

There is a post on Microsoft Docs how to deal with imperative authorization in ASP.NET Core. I think it is quite comprehensive and it answers your question about standard approach.

Also here you can find the code sample.

like image 104
Oleg Kyrylchuk Avatar answered Sep 23 '22 09:09

Oleg Kyrylchuk