I'm building out a REST API with .NET Core Web API.
My controllers simply forward requests to the service layer and return the result
[HttpPost(nameof(Create))]
public async Task<Response<ProviderDTO>> Create([FromBody] ProviderDTO provider)
=> await providerService.CreateAsync(provider);
I'm at the point in the system now where I need to start implementing authorization.
.NET Core has a lot of options to implement authorization, but the documentation predominantly discusses these approaches in the context of the Web layer (where the controllers obviously live).
My instincts are telling me that I need to be implementing the authorization within the service layer itself, rather than placing this authorization on the web layer.
Some of my reasoning includes:
- Service layer could get called by something other than a controller (for example, services calling other services, which wouldn't be concerned at that point with authorization).
- Service authorization can be unit tested directly, rather than having to rely on integration tests being written for each "layer" that goes in front of the services.
- Saves multiple calls to the database -- if I need to authorize a document in an authorization requirement if it passed I'd then have to pull the same document out later in the service.
Question One
Would it be a sensible approach to inject IPrincipal
and IAuthorizationService
into my services and handle authorization directly in there? Then the web layer would purely just check the user is logged in, and perhaps some simpler policy based attributes (i.e. this controller only allows staff policy for example)
Question Two
Does anyone have any resources they could link me through to (I did research, but there's not much out there on this)
PS: Regarding rejecting requests in the service layer, I have an exception handling middleware that converts custom exceptions to HTTP responses. Thus, if an unauthorized request occurs, I will be throwing some for of Unauthorized exception which will ultimately result in a HTTP 403.