Should i do authorization on my Domain Services?

408 views Asked by At

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.

2

There are 2 answers

14
Khanh TO On BEST ANSWER

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.

1
kayess On

While I totally agree with the logic of @KhanhTO, I would extend this with, as this is your service layer, other than attribute, i would rather inject in an authorization services interface that would do the checks with the logged in user, eg. to see if that he has correct permissions associated to his credentials to execute the given command.