asp.net-coreauthenticationauthorization

Is it okay to check user claims in AuthorizationHandler only if a route parameter requires users to be authorized?


I have an endpoing that has a route like this: api/{gifts}/get. The problem is that gifts could be whether free or not, i.e. some of them could be returned just for provided user id, and some of them should be returned for authorized users only. I came up with an idea to create a custom authentication/authorization logic where I'm checking if {gifts} are set to require authorized user in my db, and if so then the authorization won't pass if there are no required claims.

The question is how okay is it to put that kind of logic to authorization and shouldn't it be somewhere in business logic?

When I try to put it to business logic then I need to explicitly check if httpContext.User.IsAuthenticated if gifts need to, and that looks not okay as well.


Solution

  • In my opinion using the custom authentication or authorization code will be best suitable for your requirement. there is no restriction on using the business logic but based on the best practice it is better to use the custom middleware or handler for the authorization. When you think of using the Business Logic in Authorization you might face some security issue. Authorization logic is specifically focused on deciding whether or not a user has permission to perform an action, while business logic dictates what happens when they do.

    You can refer this document:

    https://learn.microsoft.com/en-us/aspnet/core/security/authorization/iauthorizationpolicyprovider?view=aspnetcore-8.0

    https://learn.microsoft.com/en-us/aspnet/core/security/authorization/customizingauthorizationmiddlewareresponse?view=aspnetcore-8.0

    https://learn.microsoft.com/en-us/aspnet/core/security/authorization/iauthorizationpolicyprovider?view=aspnetcore-8.0