8

I am working on my first microservices based application. As most of the microservices architectures, there is an API Gateway that will reduce the number of requests a client has to make. Since this is the single entry point inside the app, I thought this is where the authorization must be checked. So I made an Authentication Microservice that will handle the login, registration and the auth check. It uses Passport with OAuth2.

In the API Gateway I want to allow some of the routes to be accessed only by the authenticated users, so a good approach would be an Auth Middleware that will capture any HTTP Request. Since the authentication can be handled only in the Authentication Microservice, my idea was to "ping" the service with the request inside my middleware, then check the response code. If it's 200, the API Gateway will continue accessing the microservices. If it's 401, the API Gateway will return 401 itself to the UI.

Here is a graphic representation of my idea: enter image description here

Now there are 2 questions:

  1. Is this a good approach for this architecture?

  2. How can I pass the request from the API Gateway (Lumen) to the Authentication Microservice (Lumen) so it can be checked?

(LE: I don't have to pass the whole request, I just had to pass the Authorize header, check the solution below)

LATER EDIT:

I have managed to solve this issue using this in the middleware:

<?php

namespace App\Http\Middleware;

use Closure;
use GuzzleHttp\Client;

class Authenticate
{
    public function handle($request, Closure $next)
    {
        if($request->header('Authorization')) {
            $url = env('AUTHORIZATION_URL') . '/auth/check';
            $client = new Client();
            $headers = ['Authorization' => $request->header('Authorization')];
            $client = $client->request('GET', $url, ['headers' => $headers]);
            $status = $client->getStatusCode();
            if($status === 200) {
                $authenticated_user = json_decode($client->getBody());
                $request->request->add(['authenticated_user' => $authenticated_user]);
                return $next($request);
            }
        }

        return response('Unauthorized.', 401);
    }
}

Using this technique, I am also appending the authenticated user to the request, so I can use the user data in controllers without making calls to the authentication microservice again. Since most routes that must be authentication protected usually use user data, this comes in handy.

Sergiu
  • 345
  • 2
  • 5
  • 18

0 Answers0