I have a problem dividing responsibilities among services.
Imagine we have following reduced number of services, communicating each other via RabbitMQ:
To implement the user creation feature: should I enforce the business restrictions in the API or in the users service?
For example, if only admins can create users with "isAdmin" property set up as true, the following options comes to my mind:
API service checks if the user is authorized and if it is, send the operation to users service. operation to users service.
Advantages: Users service is more flexible. If other service want to create users in the future is not restrained to perform anything it wants (for example, create users without a "creator user"). Data is also validated early.
Disadvantages: If the business logic is too common I have to duplicate the checks in multiple points. I have the business logic of Users split
Users service checks the authorization and returns an error to API. API pass that error to client.
Do any good practice exists? Have you faced this dilemma before? How it worked?
From Domain driven design
perspective, the authorization should be a separate bounded context. Thus, the authorization checks should be done outside the Users administration bounded context
. So, in the simplest implementation, you could use some Api services that do the actual checking, called from the Application layer. If the current authenticated user has the required permission (for example CanCreateNewUsers
) then the call to the Users administration bounded context
is allowed, otherwise is rejected with an error.
A more complex/DDD solution would be to use an Anti-coruption layer between the two bounded contexts.
Btw, I suggest you to use permissions and not roles when you do the actual checking. You can use roles in the Authorization bounded context
.