PHPackages                             klsoft/yii3-keycloak-authz - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Authentication &amp; Authorization](/categories/authentication)
4. /
5. klsoft/yii3-keycloak-authz

ActiveLibrary[Authentication &amp; Authorization](/categories/authentication)

klsoft/yii3-keycloak-authz
==========================

The package provides Keycloak authorization for the web service APIs of Yii 3.

1.0.0(6mo ago)01MITPHPPHP &gt;=8.1

Since Feb 9Pushed 6mo agoCompare

[ Source](https://github.com/klsoft-web/yii3-keycloak-authz)[ Packagist](https://packagist.org/packages/klsoft/yii3-keycloak-authz)[ Docs](https://github.com/klsoft-web/yii3-keycloak-authz)[ RSS](/packages/klsoft-yii3-keycloak-authz/feed)WikiDiscussions main Synced 1w ago

READMEChangelog (1)Dependencies (7)Versions (2)Used By (0)

YII3-KEYCLOAK-AUTHZ
===================

[](#yii3-keycloak-authz)

The package provides Keycloak authorization for the web service APIs of [Yii 3](https://yii3.yiiframework.com).

See also:

- [YII3-JWT-AUTH](https://github.com/klsoft-web/yii3-jwt-auth) - The package provides a [Yii 3](https://yii3.yiiframework.com) authentication method based on a JWT token
- [PHP-KEYCLOAK-CLIENT](https://github.com/klsoft-web/php-keycloak-client) - A PHP library that can be used to secure web applications with Keycloak

Requirement
-----------

[](#requirement)

- PHP 8.1 or higher.

Installation
------------

[](#installation)

```
composer require klsoft/yii3-keycloak-authz
```

How does it work
----------------

[](#how-does-it-work)

1. A client requests a protected web service API method using an access token.
2. The web service checks whether the access token contains the necessary permissions. If permissions exist, proceed to step 6.
3. The web service obtains a permission ticket using the access token and the permissions of the API method. It then responds with the permission ticket: `HTTP/1.1 401 Unauthorized WWW-Authenticate: UMA realm="realm name", as_uri="realm URI", ticket="permission ticket"`
4. The client obtains a Requesting Party Token (RPT) using the access token and the permission ticket.
5. The client requests a protected web service API method with the RPT.
6. The web service checks the RPT permissions. If the RPT has the necessary permissions, the request is passed to the next middleware or action. Otherwise, HTTP/1.1 403 Forbidden is returned.

How to use
----------

[](#how-to-use)

### 1. Implement Klsoft\\Yii3KeycloakAuthz\\KeycloakRepositoryInterface

[](#1-implement-klsoftyii3keycloakauthzkeycloakrepositoryinterface)

Example:

```
namespace MyNamespace;

use Klsoft\Yii3KeycloakAuthz\KeycloakRepositoryInterface;
use Klsoft\Yii3KeycloakAuthz\PermissionTicketResult;
use Klsoft\Yii3KeycloakAuthz\PermissionTicketResponse;

final class KeycloakRepository implements KeycloakRepositoryInterface
{
    public function __construct(
        private string $realm,
        private string $realmUri)
    {
    }

    public function getPermissionTicket(string $accessToken, array $permissions): PermissionTicketResult
    {
        $url = "$this->realmUri/authz/protection/permission";

        $options = [
            'http' => [
                'ignore_errors' => true,
                'method' => 'POST',
                'header' => [
                    'Content-type: application/json',
                    "Authorization: Bearer $accessToken"],
                'content' => json_encode($permissions)
            ],
        ];
        $responseData = file_get_contents($url, false, stream_context_create($options));
        $responseStatusCode = $this->getHttpResponseStatusCode($http_response_header[0]);
        if (!empty($responseData)) {
            $responseArr = json_decode($responseData, true);
            if (isset($responseArr['ticket'])) {
                return new PermissionTicketResult(new PermissionTicketResponse(
                    $this->realm,
                    $this->realmUri,
                    $responseArr['ticket']));
            }
            return new PermissionTicketResult(null, $responseStatusCode, $responseArr);
        }

        return new PermissionTicketResult(null, $responseStatusCode);
    }

    private function getHttpResponseStatusCode(string $responseHeader): int
    {
        if (preg_match("/^HTTP\/[\d.]+\s+(\d{3})\s.*$/", $responseHeader, $matches)) {
            return intval($matches[1]);
        }
        return 0;
    }
}
```

### 2. Add the realm and the realm URI to param.php

[](#2-add-the-realm-and-the-realm-uri-to-paramphp)

Example:

```
return [
    'realm' => 'myrealm',
    'realmUri' => 'http://localhost:8080/realms/myrealm',
];
```

### 3. Register dependencies

[](#3-register-dependencies)

Example:

```
use Klsoft\Yii3KeycloakAuthz\KeycloakRepositoryInterface;

KeycloakRepositoryInterface::class => [
        'class' => KeycloakRepository::class,
        '__construct()' => [
            'realm' => $params['realm'],
            'realmUri' => $params['realmUri']
        ]
    ]
```

### 4. Apply permissions.

[](#4-apply-permissions)

#### 4.1. To an action.

[](#41-to-an-action)

First, add Authorization to the application middlewares:

```
use Yiisoft\Auth\Middleware\Authentication;
use Klsoft\Yii3KeycloakAuthz\Middleware\Authorization;

Application::class => [
        '__construct()' => [
            'dispatcher' => DynamicReference::to([
                'class' => MiddlewareDispatcher::class,
                'withMiddlewares()' => [
                    [
                        Authentication::class,
                        Authorization::class,
                        FormatDataResponseAsJson::class,
                        static fn() => new ContentNegotiator([
                            'application/xml' => new XmlDataResponseFormatter(),
                            'application/json' => new JsonDataResponseFormatter(),
                        ]),
                        ErrorCatcher::class,
                        static fn(ExceptionResponderFactory $factory) => $factory->create(),
                        RequestBodyParser::class,
                        Router::class,
                        NotFoundMiddleware::class,
                    ],
                ],
            ]),
        ],
    ]
```

Then, apply permissions to an action:

```
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Message\ResponseInterface;
use Klsoft\Yii3KeycloakAuthz\Permission;

final class ProductController
{
    public function __construct(private ProductPresenterInterface $productPresenter)
    {
    }

    #[Permission(
        'product',
        ['create']
    )]
    public function create(ServerRequestInterface $request): ResponseInterface
    {
        return $this->productPresenter->createProduct($request);
    }
}
```

Example of a permission with claims:

```
#[Permission(
    'product',
    ['create'],
    ['organization' => ['acme']]
)]
public function create(ServerRequestInterface $request): ResponseInterface
```

Example of a permission with an executing claim value:

```
#[Permission(
    'product',
    ['create'],
    ['organization' => [
        '__container_entry_identifier',
        OrganizationPresenterInterface::class,
        'getOrganizationName',
        ['__request']]
    ]
)]
public function create(ServerRequestInterface $request): ResponseInterface
```

#### 4.2. To a route.

[](#42-to-a-route)

First, define the set of permissions:

```
use Psr\Container\ContainerInterface;
use Klsoft\Yii3KeycloakAuthz\Middleware\Authorization;
use Klsoft\Yii3KeycloakAuthz\Permission;

'CreateProductPermission' => static function (ContainerInterface $container) {
        return $container
            ->get(Authorization::class)
            ->withPermissions([
                new Permission('product', ['create'])
            ]);
    }
```

Then, you can apply this set to a route:

```
Route::post('/product/create')
       ->middleware('CreateProductPermission')
       ->action([ProductController::class, 'create'])
       ->name('product/create')
```

###  Health Score

31

—

LowBetter than 65% of packages

Maintenance68

Regular maintenance activity

Popularity1

Limited adoption so far

Community6

Small or concentrated contributor base

Maturity44

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 100% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Unknown

Total

1

Last Release

190d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/f4e8ac50e4ad22be84b07f4c06d28cf280d22f689c460cd385c556727e638827?d=identicon)[klsoft-web](/maintainers/klsoft-web)

---

Top Contributors

[![klsoft-web](https://avatars.githubusercontent.com/u/7967163?v=4)](https://github.com/klsoft-web "klsoft-web (1 commits)")

---

Tags

authorizationkeycloakyii3jwtapiauthorizationauthorisationkeycloakyii3

### Embed Badge

![Health badge](/badges/klsoft-yii3-keycloak-authz/health.svg)

```
[![Health](https://phpackages.com/badges/klsoft-yii3-keycloak-authz/health.svg)](https://phpackages.com/packages/klsoft-yii3-keycloak-authz)
```

###  Alternatives

[cakephp/cakephp

The CakePHP framework

8.9k20.0M1.9k](/packages/cakephp-cakephp)[typo3/cms

TYPO3 CMS is a free open source Content Management Framework initially created by Kasper Skaarhoj and licensed under GNU/GPL.

1.2k1.9M122](/packages/typo3-cms)[typo3/cms-core

TYPO3 CMS Core

3313.6M5.6k](/packages/typo3-cms-core)[tempest/framework

The PHP framework that gets out of your way.

2.3k37.6k21](/packages/tempest-framework)[mcp/sdk

Model Context Protocol SDK for Client and Server applications in PHP

1.6k2.2M145](/packages/mcp-sdk)[thecodingmachine/graphqlite

Write your GraphQL queries in simple to write controllers (using webonyx/graphql-php).

5753.4M51](/packages/thecodingmachine-graphqlite)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
