boneybone/auth-server-sdk

There is no license information available for the latest version (v1.6) of this package.

BoneyBone Auth Server Laravel SDK

v1.6 2020-06-25 10:24 UTC

README

This is the Auth Server SDK For Laravel Application using BB Auth Server engine.

To use this SDK, you need to create an BB Auth Server Application to obtain the Client ID & Client Secret.

Installation

Install the package using Composer.

composer require boneybone/auth-server-sdk

Configuration

Publish the configuration file using the vendor:publish artisan command.

php artisan vendor:publish --tag=auth-server

Change the driver for the users provider to boneybone-auth-server on the config/auth.php file.

'providers' => [
    'users' => [
        'driver' => 'boneybone-auth-server',
    ],
],

....

Set the .env variables below using your credentials.

AUTH_SERVER_CLIENT_ID="YOUR CLIENT ID"
AUTH_SERVER_CLIENT_SECRET="YOUR CLIENT SECRET"
AUTH_SERVER_REDIRECT_URI="YOUR CLIENT REDIRECT URI"
AUTH_SERVER_ENDPOINT="THE DOMAIN WHERE THE AUTH-SERVER WERE DEPLOYED"

Load the Public & Private key on the AppServiceProvider.

// Load the public key
AuthServer::loadPublicKey($pathToPublicKey);

// Load the private key.
AuthServer::loadPrivateKey($pathToPrivateKey);

Done!

Available Methods

This SDK comes with the AuthServer facade, which help you interacts with the Auth Server more easy. And below is the available methods of the AuthServer facade.

When your application need to do server-to-server action such as doing a background job on updating user entities, or running a task on a cron jobs, without user interaction or user JWT token, your application requires a Client Access Token which can be requested using the getClientAccessToken() method.

AuthServer::getClientAccessToken();

// You need to set the client_id & client_secret first on your .env file, otherwise this method will return null

Get the current user access token.

AuthServer::getAccessToken();

When your front-end application need to exchange the authorization code they got from Auth Server callback, then you can use the exhangeAuthorizationCode($code) method.

AuthServer::exchangeAuthorizationCode($code);

You can refresh the access token using the refresh_token string using the refreshAccessToken($refreshToken) method.

AuthServer::refreshAccessToken($refreshToken);

If you want directly exchange the authorization_code from Auth Server callback into JWT Token, you can use exchangeCodeIntoToken($code) method.

AuthServer::exchangeCodeIntoToken($code);

If you want to get the User data, you can use getUserInfo() method.

AuthUser::getUserInfo();

// CAUTION: This method will return null if the user access token hasn't been set yet, you can set the user access token either by directly set the token using the AuthServer::setAccessToken($token) or put your API under AuthServer middleware, the middleware will do the job for you.

Set the redirect path after successful authentication.

AuthServer::redirectTo('/home);

Destroy the current user session. You can redirect your user to /auth/deauthorize or call the logout() method.

AuthServer::logout();

If you already set the Public Key and the Private Key to your application using this SDK, you can get the key contents using the following methods.

AuthServer::getPublicKey(); // to get the contents of public key.

AuthServer::getPrivateKey() // to get the contents of private key.

Acting as Backend Server

You can use this SDK to only acting as Backend Server, maybe you have different stack for front-end, and you need to use Laravel only for backend.

To use this SDK to only acting as Backend Server, all your API should be protected under \BoneyBone\AuthServer\Middleware\AuthServerMiddleware this middleware is intercepting request, extracting user from the Request's JWT Token, Login in user to your API (even though the API should be stateless but for convenience).

On your app/Http/Kernel.php file add this middleware to the $routeMiddleware array.

$routeMiddleware = [
    ...
    'auth-server-api' => \BoneyBone\AuthServer\Middleware\AuthServerMiddleware::class,
    ...
];

Then on your routes/api.php or any route files you intended to use as an API routes, use the middleware that we just registered.

Route::middleware(['auth-server-api'])->group(function() {
    // Your Routes here.
});

Any routes under the auth-server-api middleware has access to the user that made the request using the $request->user() or regular Auth::user() facade. If the provided JWT token is valid. The user will be instance of \BoneyBone\AuthServer\BoneyBoneUser but it's okay, since those class is implement the Illuminate\Contracts\Auth\Authenticatable so you can access those User object as a App\User instance. It is the same instance.

Get the User's Roles & Permissions

Once you get the user from the $request->user() or the regular Auth::user() you can get the roles & permissions using the following code.

$user = Auth::user();

// Get the roles based on the current client.
$roles = $user->getRoles(); // The user roles array, based on the current client id.

// Get all assigned roles from all clients.
$roles = $user->getRoles(true); // The user roles array from all of clients that user assigned to.

// Get the user permissions based on the current client.
$permissions = $user->getPermissions(); // The array of assigned permission based on current client.

// Get all assigned permissions from all clients.
$permissions = $user->getPermissions(true); // The array of permissions from all clients that the user assigned to.

Protecting Your Routes using Permissions

You might need to allow the request to certain endpoints only for certain permissions only, For example you have Create User feature, but only a User with create-user permission that allowed to create new user. You can do it by using the AuthServerPermissionsMiddleware.

Add middleware below to your app/Http/Kernel.php file add the following middleware

// app/Http/Kernel.php


protected $routeMiddleware = [
    ...
    'permissions' => \BoneyBone\AuthServer\Middleware\AuthServerPermissionsMiddleware::class
    ...
];

And then you can use the middleware on your route alongside the required permissions.

// Single permission
Route::post('/users', 'UserController@create')->middleware('permissions:create-user);

// Multiple permissions
Route::delete('/users/1', 'UserController@delete')->middleware('permissions:delete-user,manage-staff,manage-payroll);

About

This is the Laravel SDK for the Centralized User database called Auth Server, The Auth Server is where all User Related entities are saved.

Currently, This SDK will add 3 routes to your Application which is /auth/authorize, /auth/callback, & /auth/deauthorize, The /auth/authorize Route is where your user can login to, it will redirect the user into Auth Server and after successfull authentication, the Auth Server will redirect you back into your application callback.

There is where the /auth/callback will be used, to handle the callback (including exchanging authorization_code into access token, fetching user data, handle the Authenticatable, and finally logging in the user.).

When you want your user to logout, you can redirect your user to /auth/deauthorize to deeauthorize your user session.

How this works?

Under the hood, how Laravel authentication works is because of 3 combination of UserProvider, Authenticatable and the Guards, which each part handled the Where are the credentials on every Request, Who can authenticate itself, and from Where the user can be fetched, it can be Database, Redis, Etc.

This SDK is basically extending the UserProvider and the Authenticatable, Why not the Guard?, because the default guard has been doing good enough job to get the credentials from Cookies or Session.

The UserProvider that this SDK extended is handling the Where the user data can be fetched, in this case is the Auth Server API.

And the Authenticatable is how the user data is formatted, for example is how to get the correct identifier, remember token string, and the identifier itself.