We started working on a project recently where we had to build functionality around auth and users. We decided on dividing the responsibilities as :
User service
- keeping user entity
- user related crud operations
user entity will have basic fields like User
- userId
- first name
- last name
- dob
- phone number
And auth service will have functionalities like :
- login user
- signup user
- generate and validate tokens (JWTs)
auth services contains the entity for storing credentials for a given userId
problem statement :
For some reason we feel we are doing something wrong. Because lets say we would like the user to login through emailId/password. so we could think of 2 approaches :
1 - when user tries to login using phone or email, it directly hits auth service (ignoring gateway for now). Now auth service simply contains userId and password, so it needs to translate the given emailId/phone to userId. So it calls user service and brings the user data as per emilId/phone number, Then it checks if the userId and corresponding password matched. If so, it returns user data and JWT.
But this somehow semantically feels wrong to bring the user details first from user service and then authenticating.
2 - The UI calls user service with given emailId/phone number and password. user service does the translation of email/phone to userId,then sends the userid/password to auth service. On successful authentication it auth service sends the auth token back to user service, user service adds user details to this response and sends back to UI
Can anyone please suggest that which approach seems to be better or if there isa better design to do the same
I believe the problem is that you put too much focus on the "micro" in the term microservices. In your example there is nothing that would justify the existence of a "user" service to me.
When thinking about service boundaries in a microservices design the task is not to make every service as small as possible. The boundaries should be cut along the lines of what a useful function in the business domain is (and what can be maintained by a two-pizza team). In your case the only function you describe is authentication, so that would only justify a single service.
Another word on writing your own auth module/service - There are existing open source solutions that you can use (the most widely used being keycloak). That is free to use and battle tested for security. It just happens too easily to introduce serious security flaws in your own implementation. Also you would get a rich feature set that would take many years to implement on your own.