0
votes

I am trying to understand the architecture of microservices and I have a question about how to properly authorize a user in the Api gateway or check for its existence if I have a separate User service for registration, login and token issuance. Let's say I have two services: a user service for registration, login and receiving tokens and an ordering service. They have their own databases.

I have guesses:

  1. For each request to the api gateway, make a separate request to the authorization service and check the token and user role there, and only then redirect the request to the order service.
  2. Provide Api gateway with access to the user database to verify the token and user and then redirect the request to the order service
  3. Combine Api Gateway and user service (I think it's a bad idea).

Or are there better guesses?

2

2 Answers

1
votes

I think you have a lot of ways to do that.

I can tell how you can do it (as I'm doing) using a serverless architecture in AWS:

You can create your services (lambdas), configure a JWT authorizer (API Gateway), and use your authorizer for your functions, with the option to define the required permissions (scopes) for each function. That you can do without any custom code.

here you can see a better explanation about how it works

You can also write your own authorizer function, which will validate the requests.

p.s. API Gateway can cache the result so your authorizer doesn't need to be called for every single request.

Don't know if you wanna manage the infrastructure by yourself or use some service from a cloud provider, but I think it can at least give you a clue on how to design this kind of thing.

1
votes

I will make some assumptions and say that you are talking about JWT tokens and authorization is done using OAuth2.

After the user authentication is done, with some steps in between, the user will end up having a JWT token. This JWT token contains 3 parts inside, one of them being the signature. This signature is encrypted and cannot be deciphered without a key while the rest of the JWT content is plain text. The content of the token, together with the signature are signed on the authorization server with a key. Anybody who owns the key can read the message. This key is also a way of identifying who was the issuer of the token. That way you can say you trust this token because it has been emitted by someone you trust. Any change in a token, without re-encryption, will result in having an invalid token. A token contains also grants/privileges.

Be aware that the mentioned "key" may vary depending on the encryption algorithm.

Based on this you don't need to check every single request against the database user.

For a better understanding please take a look over OAuth2 protocol (and maybe OIDC).

Also https://www.taithienbo.com/how-can-you-trust-a-jwt-to-be-authentic/