{"id":14987336,"url":"https://github.com/agungsugiarto/codeigniter4-authentication-jwt","last_synced_at":"2025-04-12T00:02:05.670Z","repository":{"id":40395138,"uuid":"342213624","full_name":"agungsugiarto/codeigniter4-authentication-jwt","owner":"agungsugiarto","description":"JSON Web Token for codeigniter4-authentication. This package is port from tymondesigns/jwt-auth for compability with agungsugiarto/codeigniter4-authentication.","archived":false,"fork":false,"pushed_at":"2022-05-11T06:15:49.000Z","size":120,"stargazers_count":27,"open_issues_count":1,"forks_count":7,"subscribers_count":3,"default_branch":"master","last_synced_at":"2025-03-25T19:51:07.261Z","etag":null,"topics":["auth","authentication","codeigniter4","jwt","jwt-authentication"],"latest_commit_sha":null,"homepage":"","language":"PHP","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/agungsugiarto.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":".github/CONTRIBUTING.md","funding":".github/FUNDING.yml","license":"LICENSE.md","code_of_conduct":".github/CODE_OF_CONDUCT.md","threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null},"funding":{"custom":"https://saweria.co/agungsugiarto"}},"created_at":"2021-02-25T10:53:58.000Z","updated_at":"2024-03-24T03:32:27.000Z","dependencies_parsed_at":"2022-08-09T19:10:48.317Z","dependency_job_id":null,"html_url":"https://github.com/agungsugiarto/codeigniter4-authentication-jwt","commit_stats":null,"previous_names":[],"tags_count":2,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/agungsugiarto%2Fcodeigniter4-authentication-jwt","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/agungsugiarto%2Fcodeigniter4-authentication-jwt/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/agungsugiarto%2Fcodeigniter4-authentication-jwt/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/agungsugiarto%2Fcodeigniter4-authentication-jwt/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/agungsugiarto","download_url":"https://codeload.github.com/agungsugiarto/codeigniter4-authentication-jwt/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":248059172,"owners_count":21040896,"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":["auth","authentication","codeigniter4","jwt","jwt-authentication"],"created_at":"2024-09-24T14:14:28.233Z","updated_at":"2025-04-12T00:02:05.633Z","avatar_url":"https://github.com/agungsugiarto.png","language":"PHP","funding_links":["https://saweria.co/agungsugiarto"],"categories":[],"sub_categories":[],"readme":"# CodeIgniter4 Authentication JWT\n\n[![Latest Stable Version](https://poser.pugx.org/agungsugiarto/codeigniter4-authentication-jwt/v)](https://github.com/agungsugiarto/codeigniter4-authentication-jwt/releases)\n[![Total Downloads](https://poser.pugx.org/agungsugiarto/codeigniter4-authentication-jwt/downloads)](https://packagist.org/packages/agungsugiarto/codeigniter4-authentication-jwt/stats)\n[![Latest Unstable Version](https://poser.pugx.org/agungsugiarto/codeigniter4-authentication-jwt/v/unstable)](https://packagist.org/packages/agungsugiarto/codeigniter4-authentication-jwt)\n[![License](https://poser.pugx.org/agungsugiarto/codeigniter4-authentication-jwt/license)](https://github.com/agungsugiarto/codeigniter4-authentication-jwt/blob/master/LICENSE.md)\n## About\nJSON Web Token for codeigniter4-authentication. This package is port from [tymondesigns/jwt-auth](https://github.com/tymondesigns/jwt-auth) for compability with [agungsugiarto/codeigniter4-authentication](https://github.com/agungsugiarto/codeigniter4-authentication).\n\n## Documentation\n### Install Via Composer\n```sh\ncomposer require agungsugiarto/codeigniter4-authentication-jwt\n```\n\n### Copy the config\nCopy the config file from `vendor/agungsugiarto/codeigniter4-authentication-jwt/src/Config/JWT.php` to config folder of your codeigniter4 application and change class extends from `BaseConfig` to `\\Fluent\\JWTAuth\\Config\\JWT`\n\n### Update your User entities\nFirstly you need to implement the `Fluent\\JWTAuth\\Contracts\\JWTSubjectInterface` contract on your User entities, which requires that you implement the 2 methods `getJWTIdentifier()` and `getJWTCustomClaims()`.\n\nThe example below should give you an idea of how this could look. Obviously you should make any changes, as necessary, to suit your own needs.\n```php\nnamespace App\\Entities;\n\n//..\nuse Fluent\\JWTAuth\\Contracts\\JWTSubjectInterface;\n\nclass User extends Entity implements\n    //..\n    JWTSubjectInterface\n{\n    /**\n     * {@inheritdoc}\n     */\n    public function getJWTIdentifier()\n    {\n        return $this-\u003eid;\n    }\n\n    /**\n     * {@inheritdoc}\n     */\n    public function getJWTCustomClaims()\n    {\n        return [];\n    }\n}\n```\n\n### Adding `\\Fluent\\JWTAuth\\JWTGuard::class` Guards\n\nWe need to define `\\Fluent\\JWTAuth\\JWTGuard::class` authentication guards using the `extend` method on the `Auth` facade or service. You should place your call to the `extend` method within a service provider. Since codeigniter4-authentication already ships with an AuthServiceProvider, we can place the code in that provider. Open `\\App\\Providers\\AuthServiceProvider`:\n```php\nnamespace App\\Providers;\n\nuse Fluent\\Auth\\AbstractServiceProvider;\nuse Fluent\\Auth\\Facades\\Auth;\nuse Fluent\\JWTAuth\\Config\\Services;\nuse Fluent\\JWTAuth\\JWTGuard;\n\nclass AuthServiceProvider extends AbstractServiceProvider\n{\n    /**\n     * {@inheritdoc}\n     */\n    public static function register()\n    {\n        Auth::extend(JWTGuard::class, function ($auth, $name, array $config) {\n            return new JWTGuard(\n                Services::getSharedInstance('jwt'),\n                Services::getSharedInstance('request'),\n                $auth-\u003ecreateUserProvider($config['provider']),\n            );\n        });\n    }\n}\n```\n### Configure Auth guard\n\nInside the `app/Config/Auth.php` file you will need to make a few changes to configure codeigniter4-authentication to use the jwt guard to power your application authentication.\n\nMake the following changes to the file:\n```php\npublic $guards = [\n    //..\n    'api' =\u003e [\n        'driver' =\u003e \\Fluent\\JWTAuth\\JWTGuard::class,\n        'provider' =\u003e 'users',\n    ],\n];\n```\n\nHere we are telling the api guard to use the `\\Fluent\\JWTAuth\\JWTGuard::class` driver, and we are setting the api guard.\n\nNext we need to register this `App\\Providers\\AuthServiceProvider` to lifecycle application. Open `App\\Config\\Events` add this line:\n```php\nEvents::on('pre_system', [\\App\\Providers\\AuthServiceProvider::class, 'register']);\n```\n\nWe can now use codeigniter4-authentication built in Auth system, with codeigniter4-authentication-jwt doing the work behind the scenes!\n\n### Add some basic authentication routes\nFirst let's add some routes in app/Config/Routes.php as follows:\n```php\n$routes-\u003egroup('jwt', function ($routes) {\n    $routes-\u003epost('login', 'JwtauthController::login');\n    $routes-\u003epost('logout', 'JwtauthController::logout', ['filter' =\u003e 'auth:api']);\n    $routes-\u003epost('refresh', 'JwtauthController::refresh', ['filter' =\u003e 'auth:api']);\n    $routes-\u003ematch(['get', 'post'], 'user', 'JwtauthController::user', ['filter' =\u003e 'auth:api']);\n});\n```\n\n### Create the AuthController\nThen create the `JwtauthController`, either manually or by running the spark command:\n```sh\nphp spark make:controller JwtauthController\n```\nThen add the following:\n```php\n\u003c?php\n\nnamespace App\\Controllers;\n\nuse App\\Controllers\\BaseController;\nuse CodeIgniter\\API\\ResponseTrait;\n\nclass JwtauthController extends BaseController\n{\n    use ResponseTrait;\n\n    /**\n     * Get a JWT via given credentials.\n     *\n     * @return \\CodeIgniter\\Http\\Response\n     */\n    public function login()\n    {\n        // Validate this credentials request.\n        if (! $this-\u003evalidate(['email' =\u003e 'required|valid_email', 'password' =\u003e 'required'])) {\n            return $this-\u003efail($this-\u003evalidator-\u003egetErrors());\n        }\n\n        $credentials = [\n            'email' =\u003e $this-\u003erequest-\u003egetPost('email'),\n            'password' =\u003e $this-\u003erequest-\u003egetPost('password')\n        ];\n\n        if (! $token = auth('api')-\u003eattempt($credentials)) {\n            return $this-\u003efail(lang('Auth.failed'), 401);\n        }\n\n        return $this-\u003erespondWithToken($token);\n    }\n\n    /**\n     * Get the authenticated User.\n     *\n     * @return \\CodeIgniter\\Http\\Response\n     */\n    public function user()\n    {\n        return $this-\u003eresponse-\u003esetJson(auth('api')-\u003euser());\n    }\n\n    /**\n     * Log the user out (Invalidate the token).\n     *\n     * @return \\CodeIgniter\\Http\\Response\n     */\n    public function logout()\n    {\n        auth('api')-\u003elogout();\n\n        return $this-\u003eresponse-\u003esetJson(['message' =\u003e 'Successfully logged out']);\n    }\n\n    /**\n     * Refresh a token.\n     *\n     * @return \\CodeIgniter\\Http\\Response\n     */\n    public function refresh()\n    {\n        return $this-\u003erespondWithToken(auth('api')-\u003erefresh());\n    }\n\n    /**\n     * Get the token array structure.\n     *\n     * @param  string $token\n     *\n     * @return \\CodeIgniter\\Http\\Response\n     */\n    protected function respondWithToken($token)\n    {\n        return $this-\u003eresponse-\u003esetJson([\n            'access_token' =\u003e $token,\n            'token_type'   =\u003e 'bearer',\n            'expires_in'   =\u003e auth('api')-\u003efactory()-\u003egetTTL() * 60,\n        ]);\n    }\n}\n```\nYou should now be able to POST to the login endpoint (e.g. http://example.dev/jwt/login) with some valid credentials and see a response like:\n```json\n{\n    \"access_token\": \"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiYWRtaW4iOnRydWV9.TJVA95OrM7E2cBab30RMHrHDcEfxjoYZgeFONFh7HgQ\",\n    \"token_type\": \"bearer\",\n    \"expires_in\": 3600\n}\n```\nThis token can then be used to make authenticated requests to your application.\n\n### Authenticated requests\nThere are a number of ways to send the token via http:\n\n**Authorization header**\n\n```Authorization: Bearer eyJhbGciOiJIUzI1NiI...```\n\n**Query string parameter**\n\n```http://example.dev/me?token=eyJhbGciOiJIUzI1NiI...```\n\n**Post parameter**\n\n**Cookies**\n\n## Methods\nThe following methods are available on the Auth guard instance.\n\n### Multiple Guards\nIf the newly created 'api' guard is not set as a default guard or you have defined multiple guards to handle authentication, you should specify the guard when calling auth().\n\n```php\n $token = auth('api')-\u003eattempt($credentials);\n```\n\n### attempt()\nAttempt to authenticate a user via some credentials.\n\n```php\n// Generate a token for the user if the credentials are valid\n$token = auth('api')-\u003eattempt($credentials);\n```\nThis will return either a jwt or boolean\n\n### login()\nLog a user in and return a jwt for them.\n\n```php\n// Get some user from somewhere\n$user = (new UserModel())-\u003efirst();\n\n// Get the token\n$token = auth('api')-\u003elogin($user);\n```\n\n### user()\nGet the currently authenticated user.\n\n```php\n// Get the currently authenticated user\n$user = auth('api')-\u003euser();\n```\nIf the user is not then authenticated, then null will be returned.\n\n### userOrFail()\nGet the currently authenticated user or throw an exception.\n\n```php\ntry {\n    $user = auth('api')-\u003euserOrFail();\n} catch (\\Fluent\\JWTAuth\\Exceptions\\UserNotDefinedException $e) {\n    // do something\n}\n```\nIf the user is not set, then a `Fluent\\JWTAuth\\Exceptions\\UserNotDefinedException` will be thrown\n\n### logout()\nLog the user out - which will invalidate the current token and unset the authenticated user.\n\n```php\nauth('api')-\u003elogout();\n\n// Pass true to force the token to be blacklisted \"forever\"\nauth('api')-\u003elogout(true);\n```\n\n### refresh()\nRefresh a token, which invalidates the current one\n\n```php\n$newToken = auth('api')-\u003erefresh();\n\n// Pass true as the first param to force the token to be blacklisted \"forever\".\n// The second parameter will reset the claims for the new token\n$newToken = auth('api')-\u003erefresh(true, true);\n```\n\n### invalidate()\nInvalidate the token (add it to the blacklist)\n\n```php\nauth('api')-\u003einvalidate();\n\n// Pass true as the first param to force the token to be blacklisted \"forever\".\nauth('api')-\u003einvalidate(true);\n```\n\n### tokenById()\nGet a token based on a given user's id.\n\n```php\n$token = auth('api')-\u003etokenById(123);\n\n```\n\n### payload()\nGet the raw JWT payload\n\n```php\n$payload = auth('api')-\u003epayload();\n\n// then you can access the claims directly e.g.\n$payload-\u003eget('sub'); // = 123\n$payload['jti']; // = 'asfe4fq434asdf'\n$payload('exp') // = 123456\n$payload-\u003etoArray(); // = ['sub' =\u003e 123, 'exp' =\u003e 123456, 'jti' =\u003e 'asfe4fq434asdf'] etc\n```\n\n### validate()\nValidate a user's credentials\n\n\n```php\nif (auth('api')-\u003evalidate($credentials)) {\n    // credentials are valid\n}\n```\n\n## More advanced usage\n### Adding custom claims\n```php\n$token = auth('api')-\u003eclaims(['foo' =\u003e 'bar'])-\u003eattempt($credentials);\n```\n\n### Set the token explicitly\n```php\n$user = auth('api')-\u003esetToken('eyJhb...')-\u003euser();\n```\n\n### Set the request instance explicitly\n```php\n$user = auth('api')-\u003esetRequest($request)-\u003euser();\n```\n\n### Override the token ttl\n```php\n$token = auth('api')-\u003esetTTL(7200)-\u003eattempt($credentials);\n```\n\n## Contributing\nContributions are very welcome.\n\n## License\n\nReleased under the MIT License, see [LICENSE](LICENSE.md).\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fagungsugiarto%2Fcodeigniter4-authentication-jwt","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fagungsugiarto%2Fcodeigniter4-authentication-jwt","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fagungsugiarto%2Fcodeigniter4-authentication-jwt/lists"}