OAuth2 between Laravel projects
A package that allows secure communication between two or more projects, focused mainly for use in microservices architectures, adding the Oauth2 authorization standard in addition to security at the network level by IP addresses and whitelists, which may already be owned.
Features
- Simple implementation
- It does not increase the latency of requests between microservices.
- High level of security
Prerequisites
-
Having an authorization server, it is recommended to use Laravel Passport for this, specifically in the Client Credentials Grant Tokens section
-
Store the file
oauth-public.key
at folderstorage/app/
in the microservices to communicate, this file is provided by the authorization server
Installation
-
Import the library
composer require diimolabs/laravel-oauth2-client
-
Add the following environment variables:
OAUTH_HOST= OAUTH_CLIENT_ID= OAUTH_CLIENT_SECRET=
And fill with the data provided by the authorization server when creating the client corresponding to the project
-
Implement the
middleware
that validates the authorization of the input requests, in the fileapp/Http/kernel.php
protected $routeMiddleware = [ // Other middleware... 'jwt' => \Diimolabs\OAuth\Middleware\EnsureJwtIsValid::class ];
Use
Example of requesting a resource to a microservice
use Diimolabs\OAuth\Facades\OAuthClient;
use Illuminate\Support\Facades\Route;
Route::prefix('v1')->group(function(){
Route::get('message', function(){
return OAuthClient::request()
->get('http://msa-2.test/api/v1/hello-world')
->body();
});
});
Example of a request from a microservice client
use Illuminate\Support\Facades\Route;
Route::prefix('v1')->middleware('jwt')->group(function ()
{
Route::get('/hello-world', function ()
{
return 'Hello world from microservice 2';
});
});
Extra
import the configuration file using:
php artisan vendor:publish --tag=oauth-client
in external_services
you can manage the urls of your different services