Introduction - evansims/openfga-php GitHub Wiki
This guide takes you through building your first authorization. You'll install the SDK, connect to OpenFGA, and check your first permission.
Authorization with OpenFGA boils down to three things:
- A store, which acts like a database for your permissions.
- An authorization model, which defines what permissions exist. Like "documents can have viewers and editors."
- The relationship tuples, which establish specific permissions between users and resources. Like "Alice can view document:readme."
With those elements in place, you can then use permission queries to have OpenFGA answer questions like "can Alice edit this document?"
The quickest method is Docker — one command gets you up and running:
docker run -d -p 8080:8080 --name openfga openfga/openfga run
Your server is now accessible at http://localhost:8080
.
Use Composer to add the SDK to your application:
composer require evansims/openfga-php
In some cases you may need to install additional dependencies for the SDK.
Begin integrating the SDK by initializing an SDK Client in your application:
<?php
declare(strict_types=1);
use OpenFGA\Client;
use function OpenFGA\{allowed, dsl, model, store, tuple, write};
$client = new Client(
url: $_ENV['FGA_API_URL'] ?? 'http://localhost:8080',
);
In a production environment you'll want authentication and error handling.
$storeId = store(
name: 'example-document-system',
client: $client,
);
echo "Created store: {$storeId}\n";
$dsl = <<<'DSL'
model
schema 1.1
type user
type document
relations
define viewer: [user]
define editor: [user]
DSL;
$model = dsl(
dsl: $dsl,
client: $client,
);
$modelId = model(
model: $model,
store: $storeId,
client: $client,
);
echo "Created model: {$modelId}\n";
write(
client: $client,
store: $storeId,
model: $modelId,
tuples: tuple('user:alice', 'viewer', 'document:readme'),
);
echo "Granted alice viewer permission on readme\n";
$canView = allowed(
client: $client,
store: $storeId,
model: $modelId,
tuple: tuple('user:alice', 'viewer', 'document:readme'),
);
echo $canView ? '✅ Alice can view readme' : '❌ Access denied';
- Make sure your OpenFGA server is running
- Save the code as
example.php
- Run
php example.php