{"id":16296766,"url":"https://github.com/pgaultier/yii2-oauth2","last_synced_at":"2025-06-21T10:32:34.835Z","repository":{"id":57062985,"uuid":"72646955","full_name":"pgaultier/yii2-oauth2","owner":"pgaultier","description":"OAuth2 wrapper for Yii2 applications","archived":false,"fork":false,"pushed_at":"2023-11-29T18:59:57.000Z","size":808,"stargazers_count":61,"open_issues_count":0,"forks_count":18,"subscribers_count":11,"default_branch":"devel","last_synced_at":"2025-01-17T06:06:24.979Z","etag":null,"topics":["oauth2-server","yii2"],"latest_commit_sha":null,"homepage":null,"language":"PHP","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"other","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/pgaultier.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG.md","contributing":null,"funding":null,"license":"LICENSE.md","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2016-11-02T14:18:53.000Z","updated_at":"2024-02-29T07:55:37.000Z","dependencies_parsed_at":"2024-12-26T12:07:09.439Z","dependency_job_id":"c9431a07-a22e-4641-b29c-181f55ebdb4a","html_url":"https://github.com/pgaultier/yii2-oauth2","commit_stats":{"total_commits":200,"total_committers":5,"mean_commits":40.0,"dds":0.06499999999999995,"last_synced_commit":"cac778b771d6e79794f644b58adc0920c33aa1da"},"previous_names":[],"tags_count":9,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/pgaultier%2Fyii2-oauth2","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/pgaultier%2Fyii2-oauth2/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/pgaultier%2Fyii2-oauth2/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/pgaultier%2Fyii2-oauth2/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/pgaultier","download_url":"https://codeload.github.com/pgaultier/yii2-oauth2/tar.gz/refs/heads/devel","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":235448546,"owners_count":18991894,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["oauth2-server","yii2"],"created_at":"2024-10-10T20:23:54.951Z","updated_at":"2025-01-24T14:12:45.919Z","avatar_url":"https://github.com/pgaultier.png","language":"PHP","funding_links":[],"categories":[],"sub_categories":[],"readme":"Oauth2 Yii2 integration\n=======================\n\nThis extension allow the developper to use [Oauth2](https://bshaffer.github.io/oauth2-server-php-docs/) server.\n\n[![Latest Stable Version](https://poser.pugx.org/sweelix/yii2-oauth2-server/v/stable)](https://packagist.org/packages/sweelix/yii2-oauth2-server)\n[![Build Status](https://api.travis-ci.org/pgaultier/yii2-oauth2.svg?branch=master)](https://travis-ci.org/pgaultier/yii2-oauth2)\n[![Scrutinizer Code Quality](https://scrutinizer-ci.com/g/pgaultier/yii2-oauth2/badges/quality-score.png?b=master)](https://scrutinizer-ci.com/g/pgaultier/yii2-oauth2/?branch=master)\n[![Code Coverage](https://scrutinizer-ci.com/g/pgaultier/yii2-oauth2/badges/coverage.png?b=master)](https://scrutinizer-ci.com/g/pgaultier/yii2-oauth2/?branch=master)\n[![License](https://poser.pugx.org/sweelix/yii2-oauth2-server/license)](https://packagist.org/packages/sweelix/yii2-oauth2-server)\n\n[![Latest Development Version](https://img.shields.io/badge/unstable-devel-yellowgreen.svg)](https://packagist.org/packages/sweelix/yii2-oauth2-server)\n[![Build Status](https://travis-ci.org/pgaultier/yii2-oauth2.svg?branch=devel)](https://travis-ci.org/pgaultier/yii2-oauth2)\n[![Scrutinizer Code Quality](https://scrutinizer-ci.com/g/pgaultier/yii2-oauth2/badges/quality-score.png?b=devel)](https://scrutinizer-ci.com/g/pgaultier/yii2-oauth2/?branch=devel)\n[![Code Coverage](https://scrutinizer-ci.com/g/pgaultier/yii2-oauth2/badges/coverage.png?b=devel)](https://scrutinizer-ci.com/g/pgaultier/yii2-oauth2/?branch=devel)\n[![composer.lock](https://poser.pugx.org/sweelix/yii2-oauth2-server/composerlock)](https://packagist.org/packages/sweelix/yii2-oauth2-server)\n\nInstallation\n------------\n\nIf you use Packagist for installing packages, then you can update your composer.json like this :\n\n``` json\n{\n    \"require\": {\n        \"sweelix/yii2-oauth2-server\": \"~1.2.0\"\n    }\n}\n```\n\nHow to use it\n------------\n\nAdd extension to your configuration :\n\n``` php\nreturn [\n    //....\n    'bootstrap' =\u003e [\n        //....\n        'oauth2',\n        //....\n    ],\n    'modules' =\u003e [\n        //....\n        'oauth2' =\u003e [\n            'class' =\u003e 'sweelix\\oauth2\\server\\Module',\n            'backend' =\u003e BACKEND,\n            'db' =\u003e DB,\n            'identityClass' =\u003e 'app\\models\\User', // only if you don't want to use the user identityClass\n            //\n            // Parameters\n            //\n        ],\n        //....\n    ],\n    //....\n];\n```\n\nYou also need to enable PrettyUrl:\n\n```php\n'components' =\u003e [\n    //....\n    'urlManager' =\u003e [\n        'enablePrettyUrl' =\u003e true,\n        'rules' =\u003e [\n            // your rules go here\n        ],\n        // ....\n    ]\n    // ....\n]\n```\n\n### Migrations (MySql only)\n\nAll the migrations needed can be found inside src/migrations. Be sure to configure the database connection before applying them.\n\n### Grant types\n\nYou can find examples and explanations about every grant types [here](http://bshaffer.github.io/oauth2-server-php-docs/grant-types/authorization-code/)\nand [here](https://alexbilbie.com/guide-to-oauth-2-grants/).\n\nFor the Jwt Bearer Grant, you will need to create a Jwt entry in your database for the given client and subject.\n\nConfigure Module\n----------------\n\n### Basic module parameters\n\n * `backend` : can be **redis** or **mysql**\n * `db` : id of the component or connection or connection configuration\n * `identityClass` : user class used to link oauth2 authorization system default to user component `identityClass`\n * `webUserParamId` : allow separation between main app user (session) and module app user, (default to **__oauth2**)\n * `identityCookieName` : allow separation between main app user (cookie) and module app user, (default to **oauth2**)\n * `webUser` : allow full management of module web user, (default to **[]**)\n * `baseEndPoint` : base path for token and authorize endpoints default to `''`\n    * Token endpoint https://host.xxx/token\n    * Authorize endpoint https://host.xxx/authorize\n * `overrideLayout` : override module layout to use another one (ex: @app/views/layouts/oauth2)\n * `overrideViewPath` : override view path to use specific one (ex: @app/views/oauth2)   \n\n### Grants management \n \n * `allowImplicit` : allow implicit grant (default to **false**)\n * `allowAuthorizationCode` : allow authorization code grant (default to **true**)\n * `allowClientCredentials` : allow client credentials grant (default to **true**)\n * `allowPassword` : allow user credentials / password grant (default to **true**)\n * `allowCredentialsInRequestBody` : allow credentials in request body (default to **true**)\n * `allowPublicClients` : allow public clients (default to **true**)\n * `alwaysIssueNewRefreshToken` : always issue refresh token (default to **true**)\n * `unsetRefreshTokenAfterUse` : unset refresh token after use (default to **true**) \n\n### JWT parameters (:warning: Not sure about the implementation. Use at your own risk !)\n\n * `useJwtAccessToken` : send access tokens as JWT (default : **false**)\n * `allowAlgorithm` : available algorithm for JWT (default : **['RS256', 'RS384', 'RS512']**)\n * `jwtAudience` : default to token endpoint\n * `storeEncryptedTokenString` : store encrypted token (default : **true**)\n\n### Time To Live\n\n * `idTTL` : TTL of ID Token (default to **3600**)\n * `accessTokenTTL` : TTL of access token (default to **3600**)\n * `refreshTokenTTL` : TTL of refresh token (default to **14 * 24 * 3600**)\n\n### Basic Oauth names\n\n * `realm` : Realm value (default to **Service**)\n * `tokenQueryName` : name of the access token parameter (default to **access_token**)\n * `tokenBearerName` : name of authorization header (default to **Bearer**)\n\n### Enforce parameters\n \n * `enforceState` : enforce state parameter (default to **true**)\n * `allowOnlyRedirectUri` : need exact redirect URI (default to **true**)\n\n### OpenID\n\n * `allowOpenIdConnect` : enable openId connect (default : **false**) // not implemented yet\n\n### Authorization Code parameters\n\n * `enforceRedirect` : enforce redirect parameter (default to **false**)\n * `authorizationCodeTTL` : TTL of authorization code (default to **30**)\n\n### CORS\n\n * `cors` : enable `CORS` on the token endpoint (default : **false**) the CORS part can be defined using an array as described [in Yii documentation](http://www.yiiframework.com/doc-2.0/yii-filters-cors.html)\n \n``` php\n return [\n     //....\n     'bootstrap' =\u003e [\n         //....\n         'oauth2',\n         //....\n     ],\n     'modules' =\u003e [\n         //....\n         'oauth2' =\u003e [\n             'class' =\u003e 'sweelix\\oauth2\\server\\Module',\n             'backend' =\u003e 'redis',\n             'db' =\u003e 'redis',\n             'identityClass' =\u003e 'app\\models\\User', // only if you don't want to use the user identityClass\n             //\n             // Cors parameters example :\n             //\n             'cors' =\u003e [\n                'Origin' =\u003e ['https://www.myowndomain.com'],\n             ]\n         ],\n         //....\n     ],\n     //....\n ];\n\n```\n \nUser identity and Web user\n--------------------------\n\nConfigure the user component to link oauth2 system and user / identity management\n\n``` php\nreturn [\n    //....\n    'components' =\u003e [\n        //....\n        'user' =\u003e [\n            'class' =\u003e 'sweelix\\oauth2\\server\\web\\User',\n            'identityClass' =\u003e 'app\\models\\User', // Identity class must implement UserModelInterface\n            //\n            // Parameters\n            //\n        ],\n        //....\n    ],\n    //....\n];\n```\n\n`IdentityClass` must implements `sweelix\\oauth2\\server\\interfaces\\UserModelInterface`. You can use the trait\n`sweelix\\oauth2\\server\\traits\\IdentityTrait` to automagically implement \n\n * `public function getRestrictedScopes()`\n * `public function setRestrictedScopes($scopes)`\n * `public static function findIdentityByAccessToken($token, $type = null)`\n\nyou will have to implement the remaining methods : \n\n * `public static function findByUsernameAndPassword($username, $password)`\n * `public static function findByUsername($username)`\n\nCreating specific view for OAuth2\n---------------------------------\n\nIn order to use your own views (instead of the builtin ones), you can override \n * `layout` : module parameter `overrideLayout`\n * `viewPath` : module parameter `overrideViewPath`\n \n### Overriding layout\n \nYou should create a classic layout like :\n \n```php\n\u003c?php\n/**\n * @app/views/layouts/newLayout.php\n * @var string $content\n */\nuse yii\\helpers\\Html;\n\n$this-\u003ebeginPage(); ?\u003e\n    \u003c!DOCTYPE html\u003e\n    \u003chead\u003e\n        \u003cmeta charset=\"utf-8\"\u003e\n        \u003cmeta http-equiv=\"X-UA-Compatible\" content=\"IE=edge\"\u003e\n        \u003ctitle\u003e\u003c?php echo Html::encode($this-\u003etitle); ?\u003e\u003c/title\u003e\n\n        \u003cmeta name=\"viewport\" content=\"width=device-width, initial-scale=1\"\u003e\n\n        \u003c?php $this-\u003ehead(); ?\u003e\n    \u003c/head\u003e\n    \u003cbody\u003e\n        \u003c?php $this-\u003ebeginBody(); ?\u003e\n            \u003c?php echo $content;?\u003e\n        \u003c?php $this-\u003eendBody(); ?\u003e\n    \u003c/body\u003e\n\n\u003c/html\u003e\n\u003c?php $this-\u003eendPage();\n\n``` \n\nand link it to the module\n\n```php\nreturn [\n    //....\n    'modules' =\u003e [\n        //....\n        'oauth2' =\u003e [\n            'class' =\u003e 'sweelix\\oauth2\\server\\Module',\n            'overrideLayout' =\u003e '@app/views/layouts/newLayout',\n            //\n            // Additional Parameters\n            //\n        ],\n        //....\n    ],\n    //....\n];\n```\n\n### Overriding views\n \nYou should create 3 views to allow oauth2 module to work as expected and link them to the module\n\n```php\nreturn [\n    //....\n    'modules' =\u003e [\n        //....\n        'oauth2' =\u003e [\n            'class' =\u003e 'sweelix\\oauth2\\server\\Module',\n            // use views in folder oauth2\n            'overrideViewPath' =\u003e '@app/views/oauth2',\n            //\n            // Additional Parameters\n            //\n        ],\n        //....\n    ],\n    //....\n];\n```\n \n#### Error view\n \nThis view is used to display a page when an error occurs\n \n```php\n\u003c?php\n/**\n * error.php\n *\n * @var string $type error type\n * @var string $description error description\n */\nuse yii\\helpers\\Html;\n?\u003e\n\n    \u003ch1 class=\"alert-heading\"\u003e\u003c?php echo ($type ? : 'Unkown error'); ?\u003e\u003c/h1\u003e\n    \u003cp\u003e\u003c?php echo ($description ? : 'Please check your request'); ?\u003e\u003c/p\u003e\n\n``` \n\n\n#### Login view\n \nThis view is used to display a login page when needed\n \n```php\n\u003c?php\n/**\n * login.php\n *\n * @var \\sweelix\\oauth2\\server\\forms\\User $user\n *\n */\nuse yii\\helpers\\Html;\n?\u003e\n    \u003c?php echo Html::beginForm('', 'post', ['novalidate' =\u003e 'novalidate']); ?\u003e\n        \u003clabel\u003eUsername\u003c/label\u003e\n        \u003c?php echo Html::activeTextInput($user, 'username', [\n            'required' =\u003e 'required',\n        ]); ?\u003e\n        \u003cbr/\u003e\n    \n        \u003clabel\u003ePassword\u003c/label\u003e\n        \u003c?php echo Html::activePasswordInput($user, 'password', [\n            'required' =\u003e 'required',\n        ]); ?\u003e\n        \u003cbr/\u003e\n        \u003cbutton type=\"submit\"\u003eLOGIN\u003c/button\u003e\n    \u003c?php echo Html::endForm(); ?\u003e\n\n``` \n\n#### Authorize view\n \nThis view is used to display an authorization page when needed\n \n```php\n\u003c?php\n/**\n * authorize.php\n *\n * @var \\sweelix\\oauth2\\server\\interfaces\\ScopeModelInterface[] $requestedScopes\n * @var \\sweelix\\oauth2\\server\\interfaces\\ClientModelInterface $client\n *\n */\nuse yii\\helpers\\Html;\n?\u003e\n    \u003ch1\u003e\u003c?php echo $client-\u003ename ?\u003e \u003cspan\u003erequests access\u003c/span\u003e\u003c/h1\u003e\n    \n    \u003c?php echo Html::beginForm(); ?\u003e\n        \u003c?php if(empty($requestedScopes) === false) : ?\u003e\n        \u003cul\u003e\n            \u003c?php foreach($requestedScopes as $scope): ?\u003e\n            \u003cli\u003e\n                \u003ch4\u003e\u003c?php echo $scope-\u003eid; ?\u003e\u003c/h4\u003e\n                \u003cp\u003e\n                    \u003c?php echo $scope-\u003edefinition; ?\u003e\n                \u003c/p\u003e\n            \u003c/li\u003e\n            \u003c?php endforeach; ?\u003e\n        \u003c/ul\u003e\n        \u003c?php endif; ?\u003e\n            \u003c!-- name of decline button **must be** decline --\u003e\n            \u003cbutton type=\"submit\" name=\"decline\"\u003eDECLINE\u003c/button\u003e\n            \u003c!-- name of accept button **must be** accept --\u003e\n            \u003cbutton type=\"submit\" name=\"accept\"\u003eAUTHORIZE\u003c/button\u003e\n    \u003c?php echo Html::endForm(); ?\u003e\n\n``` \n\nExposed Models overview\n-----------------------\n\nThe Oauth2 Yii2 extension expose severall models which can be used in your application.\nAll models can be overloaded using Yii2 DI.\n\nFor example, if you want to overload the `Client` model, you have to inject your own model in the DI using:\n\n```php\n\nYii::$container-\u003eset('sweelix\\oauth2\\server\\interfaces\\ClientModelInterface', [\n    'class' =\u003e YourClientModel::className(),\n]);\n```\n\n### Client / ClientModelInterface\n\n * `Client::findOne($id)` - Find client by ID\n * `Client::findAllByUserId($id)` - Find all clients accepted by user (userId)\n * `Client::findAll()` - Find all existing clients\n * `$client-\u003esave()` - Save client\n * `$client-\u003edelete()` - Delete client\n * `$client-\u003ehasUser($userId)` - Check if user (userId) has accepted the client\n * `$client-\u003eaddUser($userId)` - Attach the user (userId) to the client\n * `$client-\u003eremoveUser($userId)` - Dettach the user (userId) from the client\n \n### AccessToken / AccessTokenModelInterface\n\n * `AccessToken::findOne($id)` - Find accessToken by ID\n * `AccessToken::findAllByUserId($id)` - Find all accessTokens for user (userId)\n * `AccessToken::findAllByClientId($id)` - Find all accessTokens for client (clientId)\n * `AccessToken::deleteAllByUserId($id)` - Delete all accessTokens for user (userId)\n * `AccessToken::deleteAllByClientId($id)` - Delete all accessTokens for client (clientId)\n * `AccessToken::findAll()` - Find all existing accessTokens\n * `AccessToken::deleteAllExpired()` - Delete all expired accessTokens\n * `$accessToken-\u003esave()` - Save accessToken\n * `$accessToken-\u003edelete()` - Delete accessToken\n\n### RefreshToken / RefreshTokenModelInterface\n\n * `RefreshToken::findOne($id)` - Find accessToken by ID\n * `RefreshToken::findAllByUserId($id)` - Find all refreshTokens for user (userId)\n * `RefreshToken::findAllByClientId($id)` - Find all refreshTokens for client (clientId)\n * `RefreshToken::deleteAllByUserId($id)` - Delete all refreshTokens for user (userId)\n * `RefreshToken::deleteAllByClientId($id)` - Delete all refreshTokens for client (clientId)\n * `RefreshToken::findAll()` - Find all existing refreshTokens\n * `RefreshToken::deleteAllExpired()` - Delete all expired refreshTokens\n * `$refreshToken-\u003esave()` - Save refreshToken\n * `$refreshToken-\u003edelete()` - Delete refreshToken\n\n### AuthCode / AuthCodeModelInterface\n\n * `AuthCode::findOne($id)` - Find authCode by ID\n * `$authCode-\u003esave()` - Save authCode\n * `$authCode-\u003edelete()` - Delete authCode\n\n### Scope / ScopeModelInterface\n\n * `Scope::findOne($id)` - Find scope by ID\n * `Scope::findAvailableScopeIds()` - Find all scopes IDs\n * `Scope::findDefaultScopeIds()` - Find default scopes IDs\n * `$scope-\u003esave()` - Save scope\n * `$scope-\u003edelete()` - Delete scope\n\n### CypherKey / CypherKeyModelInterface\n\n * `CypherKey::findOne($id)` - Find cypherKey by ID\n * `$cypherKey-\u003esave()` - Save cypherKey\n * `$cypherKey-\u003edelete()` - Delete cypherKey\n * `$cypherKey-\u003egenerateKeys()` - Generate random keys for current cypherKey\n \n### Jti / JtiModelInterface (:warning: Not sure about the implementation. Use at your own risk !)\n\n * `Jti::findOne($id)` - Find jti by ID\n * `Jti::findAllBySubject($id)` - Find all jtis for user (userId)\n * `Jti::findAllByClientId($id)` - Find all jtis for client (clientId)\n * `Jti::deleteAllBySubject($id)` - Delete all jtis for user (userId)\n * `Jti::deleteAllByClientId($id)` - Delete all jtis for client (clientId)\n * `Jti::findAll()` - Find all existing jtis\n * `Jti::deleteAllExpired()` - Delete all expired jtis\n * `Jti::getFingerprint($clientId, $subject, $audience, $expires, $jti)` - Get a jti fingerprint for given params\n * `$jti-\u003esave()` - Save jti\n * `$jti-\u003edelete()` - Delete jti\n\n### Jwt / JwtModelInterface (:warning: Not sure about the implementation. Use at your own risk !)\n\n * `Jwt::findOne($id)` - Find jwt by ID\n * `Jwt::getFingerprint($clientId, $subject)` - Get jwt fingerprint for given clientId and subject\n * `$jwt-\u003esave()` - Save jwt\n * `$jwt-\u003edelete()` - Delete jwt\n\nLinking RBAC and Scope systems\n------------------------------\n\nUsing `sweelix\\oauth2\\server\\web\\User` class will automagically link `rbac` system and `oauth2` system.\n\nPermission system will be slightly modified to allow fine grained checks :\n\n * `Yii::$app-\u003euser-\u003ecan('read')` will check\n    1. if scope `read` is allowed for current client\n    2. if rbac permission `read` is allowed for current user \n \n * `Yii::$app-\u003euser-\u003ecan('rbac:read')` will check **only** if rbac permission `read` is allowed for current user \n\n * `Yii::$app-\u003euser-\u003ecan('oauth2:read')` will check **only** if scope `read` is allowed for current client\n\nRunning the tests\n-----------------\n\nBefore running the tests, you should edit the file tests/config/BACKEND.php and change the config to match your environment.\n\nCLI System\n----------\n\nSeveral commands are available to manage oauth2 system\n\n * `php protected/yii.php oauth2:client/create`\n * `php protected/yii.php oauth2:client/update`\n * `php protected/yii.php oauth2:client/delete`\n * `php protected/yii.php oauth2:jwt/create`\n * `php protected/yii.php oauth2:jwt/update`\n * `php protected/yii.php oauth2:jwt/delete`\n * `php protected/yii.php oauth2:key/create`\n * `php protected/yii.php oauth2:key/update`\n * `php protected/yii.php oauth2:key/delete`\n * `php protected/yii.php oauth2:scope/create`\n * `php protected/yii.php oauth2:scope/update`\n * `php protected/yii.php oauth2:scope/delete`\n * `php protected/yii.php oauth2:cronjob/remove-expired` - Run this one with your cron manager\n * `php protected/yii.php oauth2:migrate-redis/migrate` - Migration command for redis","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fpgaultier%2Fyii2-oauth2","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fpgaultier%2Fyii2-oauth2","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fpgaultier%2Fyii2-oauth2/lists"}