segrax / open-policy-agent
Open Policy Agent 客户端和 PSR-7、PSR-15 授权中间件
0.5.0
2024-03-06 19:26 UTC
Requires
- php: ^8.3
- psr/http-client: ^1.0
- psr/http-factory: ^1.0
- psr/http-message: ^1.0 | ^2.0
- psr/http-server-handler: ^1.0
- psr/http-server-middleware: ^1.0
- psr/log: ^1.0|^2.0|^3.0
- splitbrain/php-archive: ^1.2
Requires (Dev)
- equip/dispatch: ^2.0
- friendsofphp/php-cs-fixer: ^3.8
- guzzlehttp/guzzle: ^7.4
- phpunit/phpunit: ^10
- rector/rector: ^1
- slim/psr7: ^1.5
- vimeo/psalm: ^5
Suggests
- guzzlehttp/guzzle: Can be used as the HTTP Client
- monolog/monolog: Can be used to support logging
- tuupola/slim-jwt-auth: Can be used to validate JWTs and insert them into the request
README
本库为 Open Policy Agent (OPA) 提供客户端,OPA 是一个 PSR-15 授权中间件和一个 PSR-15 打包分发中间件。
有关工作示例,请参阅 segrax/opa-php-examples,并提供教程,以指导您通过示例。
安装
使用 composer 安装最新版本。
composer require segrax/open-policy-agent
使用示例
客户端使用
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()));
分发中间件
插入中间件,它将为具有有效 JWT 且子字段为 'opa' 的用户响应 /opa/bundles/{service_name} 的打包请求
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); });
代码测试
make tests
安全
如果您发现任何安全相关的问题,请通过电子邮件 robcrossfield@gmail.com 联系。
许可证
MIT 许可证(MIT)。有关更多信息,请参阅 许可证文件。