Skip to content

auth-server-php quickstart

Install

Terminal window
composer require vendidit/auth-server-php
# Plus a PSR-18 HTTP client + PSR-17 factories:
composer require guzzlehttp/guzzle guzzlehttp/psr7 http-interop/http-factory-guzzle

Env

AUTH_SERVER_URL=https://auth.vendidit.com
AUTH_APP_CODE=my-service
JWT_ACCESS_SECRET=<shared with auth-server>

Construct the client

use GuzzleHttp\Client as GuzzleClient;
use Http\Factory\Guzzle\RequestFactory;
use Http\Factory\Guzzle\StreamFactory;
use Vendidit\AuthServer\AuthClient;
use Vendidit\AuthServer\Config;
use Vendidit\AuthServer\Http\HttpTransport;
$config = new Config(
authServerUrl: getenv('AUTH_SERVER_URL'),
appCode: getenv('AUTH_APP_CODE'),
jwtAccessSecret: getenv('JWT_ACCESS_SECRET'),
jwtIssuer: 'ven-auth',
jwtAudience: 'ven-platform',
);
$transport = new HttpTransport(
httpClient: new GuzzleClient(),
requestFactory: new RequestFactory(),
streamFactory: new StreamFactory(),
baseUrl: rtrim($config->authServerUrl, '/') . '/api/v1',
);
$auth = AuthClient::build(config: $config, transport: $transport);

Validate a bearer

use Vendidit\AuthServer\Exceptions\VenAuthException;
try {
$principal = $auth->validateBearer($request->getHeaderLine('Authorization'));
// $principal is UserPrincipal | ServicePrincipal
} catch (VenAuthException $e) {
http_response_code($e->statusCode ?? 401);
echo json_encode(['error' => $e->code, 'message' => $e->getMessage()]);
}

Call the auth-server

// As the current user
$me = $auth->me($accessToken);
// As a service (m2m)
$serviceClient = new \Vendidit\AuthServer\Http\ServiceAuthClient(
transport: $transport,
clientId: getenv('AUTH_CLIENT_ID'),
clientSecret: getenv('AUTH_CLIENT_SECRET'),
);
$serviceToken = $serviceClient->getToken(); // cached + auto-refreshed

Permission registration on boot

use Vendidit\AuthServer\Flows\PermissionFlow;
$flows = new \Vendidit\AuthServer\Flows($transport, $config);
$flows->registerPermissions($serviceToken, [
'service' => 'orders',
'permissions' => [
['code' => 'orders:read', 'resource' => 'orders', 'action' => 'read', 'name' => 'Read orders'],
['code' => 'orders:create', 'resource' => 'orders', 'action' => 'create', 'name' => 'Create order'],
],
]);

Idempotent — safe to call every boot.