PHPackages                             klsoft/yii2-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/yii2-keycloak-authz

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

klsoft/yii2-keycloak-authz
==========================

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

1.0.0(4mo ago)00MITPHPPHP &gt;=8.0

Since Feb 9Pushed 4mo agoCompare

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

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

YII2-KEYCLOAK-AUTHZ
===================

[](#yii2-keycloak-authz)

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

See also:

- [YII2-JWT-AUTH](https://github.com/klsoft-web/yii2-jwt-auth) - The package provides a [Yii 2](https://www.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.0 or higher.

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

[](#installation)

```
composer require klsoft/yii2-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 ActionFilter or action. Otherwise, HTTP/1.1 403 Forbidden is returned

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

[](#how-to-use)

### 1. Implement Klsoft\\Yii2KeycloakAuthz\\KeycloakRepositoryInterface

[](#1-implement-klsoftyii2keycloakauthzkeycloakrepositoryinterface)

Example:

```
namespace MyNamespace;

use Klsoft\Yii2KeycloakAuthz\KeycloakRepositoryInterface;
use Klsoft\Yii2KeycloakAuthz\PermissionTicketResult;
use Klsoft\Yii2KeycloakAuthz\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 of registering dependencies using the application configuration:

```
use Klsoft\Yii2KeycloakAuthz\Authorization;
use Klsoft\Yii2KeycloakAuthz\KeycloakRepositoryInterface;

'container' => [
        'definitions' => [
            Authorization::class => [
                Authorization::class,
                [Instance::of(KeycloakRepositoryInterface::class)]
            ]
        ],
        'singletons' => [
            KeycloakRepositoryInterface::class => [
                KeycloakRepository::class,
                [
                    $params['realm'],
                    $params['realmUri']
                ]
            ]
        ]
    ]
```

### 4. Apply permissions.

[](#4-apply-permissions)

#### 4.1. Configure the `authorization` behavior and apply permissions to an action

[](#41--configure-the-authorization-behavior-and-apply-permissions-to-an-action)

Example:

```
use yii\rest\Controller;
use Klsoft\Yii2JwtAuth\HttpJwtAuth;
use Klsoft\Yii2KeycloakAuthz\Authorization;
use Klsoft\Yii2KeycloakAuthz\Permission;

class ProductController extends Controller
{
    public function __construct(
        private HttpJwtAuth $httpJwtAuth,
        private Authorization $authz,
        private ProductPresenterInterface $productPresenter)
    {
    }

    public function behaviors()
    {
        $behaviors = parent::behaviors();
        $behaviors['authentication'] = $this->httpJwtAuth;
        $behaviors['authorization'] = $this->authz;
        return $behaviors;
    }

    #[Permission(
        'product',
        ['create']
    )]
    public function actionCreate()
    {
        return $this->productPresenter->createProduct(Yii::$app->getRequest());
    }
}
```

Example of a permission with claims:

```
#[Permission(
    'product',
    ['create'],
    ['organization' => ['acme']]
)]
public function actionCreate()
```

Example of a permission with an executing claim value:

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

#### 4.2. Configure the `authorization` behavior and apply permissions to a controller

[](#42--configure-the-authorization-behavior-and-apply-permissions-to-a-controller)

Example:

```
use yii\rest\Controller;
use Klsoft\Yii2JwtAuth\HttpJwtAuth;
use Klsoft\Yii2KeycloakAuthz\Authorization;
use Klsoft\Yii2KeycloakAuthz\Permission;

final class ProductController extends Controller
{
    public function __construct(
        private HttpJwtAuth $httpJwtAuth,
        private Authorization $authz,
        private ProductPresenterInterface $productPresenter)
    {
    }

    public function behaviors()
    {
        $behaviors = parent::behaviors();
        $behaviors['authentication'] = $this->httpJwtAuth;
        $behaviors['authorization'] = $this->authz->withPermissions([
            new Permission(
                'product',
                ['create']
            ),
            new Permission(
                'product',
                ['update']
            )
        ]);
        return $behaviors;
    }
}
```

###  Health Score

31

—

LowBetter than 66% of packages

Maintenance74

Regular maintenance activity

Popularity0

Limited adoption so far

Community6

Small or concentrated contributor base

Maturity39

Early-stage or recently created project

 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

145d 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

authorizationkeycloakyii2jwtapiauthorizationauthorisationyii2keycloak

### Embed Badge

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

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

###  Alternatives

[league/oauth2-server

A lightweight and powerful OAuth 2.0 authorization and resource server library with support for all the core specification grants. This library will allow you to secure your API with OAuth and allow your applications users to approve apps that want to access their data from your API.

6.7k147.0M289](/packages/league-oauth2-server)[auth0/auth0-php

PHP SDK for Auth0 Authentication and Management APIs.

41021.9M91](/packages/auth0-auth0-php)[auth0/login

Auth0 Laravel SDK. Straight-forward and tested methods for implementing authentication, and accessing Auth0's Management API endpoints.

2795.3M3](/packages/auth0-login)[stevenmaguire/oauth2-keycloak

Keycloak OAuth 2.0 Client Provider for The PHP League OAuth2-Client

2306.4M45](/packages/stevenmaguire-oauth2-keycloak)[ovh/ovh

Wrapper for OVHcloud APIs

3092.8M29](/packages/ovh-ovh)[auth0/symfony

Symfony SDK for Auth0 Authentication and Management APIs.

128814.6k](/packages/auth0-symfony)

PHPackages © 2026

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