I have the following domain service:
pulic void DeleteCustomer(int customerId, string userIdentity, string userPassword)
{
//1º Do login operation to verify if the credentials are valid.
customerRepository.DeleteById(customerId);
}
Let's say that I am consuming this code of ASP.NET MVC or Windows Forms application that has a login window.
The login will be validated again in each operation, wasting resources.
Let's say I change it to:
pulic void DeleteCustomer (int customerId, int requestUserId)
{
//1º Trust that requestUserId is valid.
//Do something with the requestUserId (e.g Set the UserId that deleted the customer)
customerRepository.DeleteById(customerId);
}
In this case, login operation will be made by the ASP.NET MVC OR Windows Forms Application just one time but any caller can pass any requestUserId, leaving a terrible security hole.
It makes sense to do authorization in any methods that need authorization otherwise there will be a security problem, especially when these methods are entry points in your backend logic. That means if you deploy these domain services as another tier which is accessible from outside, these methods really need protection.
From defensive programming perspective, every method should be able to defend itself from invalid or fake inputs which is also applicable in this case.
From REST stateless perspective, every request should be isolated from each other which means each request should carry all the necessary information without relying on previous requests and there even should not be a server state. For that reason, all requests should be authorized independently.
Furthermore, authorization is a cross-cutting concern, you should consider writing your authorization code as an attribute.