Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Implementing authentication and authorization in clean architecture with C#

In ASP.NET Core, we can use the [Authorize] attribute on our methods in controllers. It works fine for both authentication and authorization.

But while using clean architecture, we can't do it. Authentication and authorization belongs to the application layer. (or am I wrong?)

The problem is that every time I want to authenticate or authorize something, I need to do it manually in code. It doesn't look good.

So I thought there must be better solution. I know that I could use MediatR and the pipelines, but I don't use it. Instead, I have simple interface IRequestHandler<TRequest, TResult> with HandleAsync method.

How could I perform authentication or authorization on every call to HandleAsync from classes that inherits from IRequestHandler or directly from it? How can I cancel processing of HandleAsync method if the authentication/authorization fails and return appropriate result (by appropriate I mean compatible with TResult defined in IRequestHandler)?

like image 972
Szyszka947 Avatar asked Oct 27 '25 13:10

Szyszka947


1 Answers

I think you are mixed up about what the UI layer is. All the controllers, filters, middleware, views and view models are the UI layer.

Given that Auth in ASP.NET Core is handled by filters and middleware, this means that the Auth is in the UI layer.

There is nothing wrong with marking your methods/controllers with the attributes as that is exactly what they are for.

Check this for more info (my source): https://learn.microsoft.com/en-us/dotnet/architecture/modern-web-apps-azure/common-web-application-architectures#organizing-code-in-clean-architecture

like image 67
Michael Coxon Avatar answered Oct 30 '25 11:10

Michael Coxon