I have created a
User service that controls user login using OAuth2 protocol and stores the user in the local database. So this service is aware of the user session and user identity.
Now I have another service
Foo with some endpoint
/foo. And the problem is that I need to know which user made the request to
/foo endpoint. But the problem is that
Foo service is unaware about the user and session.
What are the solutions and best practices for handling this scenario?
I have created a
The usual approach is for the authentication service to issue the user a signed token. Other services can verify the signature to check that the token is genuine. The token then contains the user ID. Don't roll your own, but use an existing approach like JWT instead. Be aware of the drawbacks: tokens cannot be revoked individually. A token is valid until it expires, or until the signing key for all tokens is revoked.
In many cases such a zero-knowledge architecture is not necessary (well, the other services do at least have to know the public key for the token signature). Your services can talk to each other. There's no general reason why the foo-service shouldn't be able to ask the user service “is this token valid and which user does it represent?”.
Note that your internal services don't have to correspond 1:1 with externally visible endpoints. E.g. it would not be unusual to provide the API through a server that just translates the requests to various internal services. This frontend or facade is also a great place to add shared concerns like authentication. Your internal services would then be firewalled of from the public, and could assume that any provided user ID has already been authenticated.