PHP code example of segrax / open-policy-agent

1. Go to this page and download the library: Download segrax/open-policy-agent library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

segrax / open-policy-agent example snippets


use Segrax\OpenPolicyAgent\Client;
use GuzzleHttp\Client as GuzzleHttpClient;

$apiPolicy = "package my.api
              default allow=false
              allow {
                  input.path = [\"abc\"]
                  input.user == \"a random user\"
              }";

$client = new Client(null, new GuzzleHttpClient(), new RequestFactory(), 'http://127.0.0.1:8181', 'MyToken');

// Push a policy to the agent
$client->policyUpdate('my/api', $apiPolicy, false);

// Execute the policy
$inputs = [ 'path' => ['abc'],
            'user' => 'a random user'];

$res = $client->policy('my/api', $inputs, false, false, false, false );
if ($res->getByName('allow') === true ) {
    // Do stuff
}

use Segrax\OpenPolicyAgent\Client;
use Segrax\OpenPolicyAgent\Middleware\Authorization;

$app = AppFactory::create();

$client = new Client(null, new GuzzleHttpClient(), new RequestFactory(), 'http://127.0.0.1:8181', 'MyToken');
$app->add(new Authorization(
                [Authorization::OPT_POLICY => 'auth/api'],
                $client,
                $app->getResponseFactory()));


use Segrax\OpenPolicyAgent\Client;
use Segrax\OpenPolicyAgent\Middleware\Distributor;

$app = AppFactory::create();

$app->add(new Distributor(
                        '/opa/bundles/',        // Route
                        __DIR__ . '/opa',       // Policy Path
                        [Distributor::OPT_AGENT_USER => 'opa'], // Token Sub Field
                        $app->getResponseFactory(),
                        new StreamFactory(),
                        $app->getLogger()));

// Add a GET route for the opa bundle route
$app->get('/opa/bundles/{name}', function (Request $request, Response $response, array $args) {
    return $response->withStatus(404);
});