Authentication - evansims/openfga-php GitHub Wiki
This guide shows you how to configure the SDK for various authentication methods and use cases.
This is the recommended authentication method when using the SDK with Auth0 FGA. The SDK handles OAuth token management automatically.
<?php
declare(strict_types=1);
use OpenFGA\Authentication\ClientCredentialAuthentication;
use OpenFGA\Client;
// Configure OpenFGA client with OAuth2 client credentials
$client = new Client(
url: $_ENV['FGA_API_URL'] ?? 'http://localhost:8080',
authentication: new ClientCredentialAuthentication(
clientId: $_ENV['FGA_CLIENT_ID'] ?? 'your-client-id',
clientSecret: $_ENV['FGA_CLIENT_SECRET'] ?? 'your-client-secret',
issuer: $_ENV['FGA_ISSUER'] ?? 'https://your-auth-server.com',
audience: $_ENV['FGA_AUDIENCE'] ?? 'https://api.your-service.com',
),
);
Environment variables:
FGA_API_URL=https://api.us1.fga.dev
FGA_CLIENT_ID=your_client_id
FGA_CLIENT_SECRET=your_client_secret
FGA_ISSUER=https://your-tenant.us.auth0.com/oauth/token
FGA_AUDIENCE=https://api.us1.fga.dev/
For simpler setups or self-hosted OpenFGA instances that support API tokens:
<?php
declare(strict_types=1);
use OpenFGA\Authentication\TokenAuthentication;
use OpenFGA\Client;
// Configure OpenFGA client with pre-shared API key
$client = new Client(
url: $_ENV['FGA_API_URL'] ?? 'http://localhost:8080',
authentication: new TokenAuthentication(
token: $_ENV['FGA_API_TOKEN'] ?? 'your-api-token',
),
);
Environment variables:
FGA_API_URL=https://your-openfga-server.com
FGA_API_TOKEN=your_api_token
- Verify your environment variables are set correctly
- Check that your client ID and secret are valid
- Ensure the issuer URL includes the full path (for example
/oauth/token
)
The SDK automatically refreshes tokens for Client Credentials authentication. If you're seeing expired token errors:
- Check your system clock is accurate
- Verify the audience URL matches your OpenFGA API endpoint exactly
If authentication isn't working locally:
- Confirm your OpenFGA server allows unauthenticated requests
- Check the server logs for authentication requirements
For comprehensive error handling patterns including authentication failures, see the Results guide which covers specific error handling for authentication errors.
Use a package like vlucas/phpdotenv for development:
if (file_exists(__DIR__ . '/.env')) {
$dotenv = Dotenv\Dotenv::createImmutable(__DIR__);
$dotenv->load();
}