{"id":13669192,"url":"https://github.com/generationtux/jwt-artisan","last_synced_at":"2025-04-05T18:11:19.350Z","repository":{"id":1622407,"uuid":"43390837","full_name":"generationtux/jwt-artisan","owner":"generationtux","description":"JWT auth for Laravel and Lumen","archived":false,"fork":false,"pushed_at":"2023-03-22T17:37:47.000Z","size":109,"stargazers_count":141,"open_issues_count":2,"forks_count":8,"subscribers_count":22,"default_branch":"master","last_synced_at":"2025-03-29T17:11:37.162Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":null,"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/generationtux.png","metadata":{"files":{"readme":"readme.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null}},"created_at":"2015-09-29T19:55:51.000Z","updated_at":"2024-10-16T21:37:18.000Z","dependencies_parsed_at":"2023-07-06T19:01:58.497Z","dependency_job_id":null,"html_url":"https://github.com/generationtux/jwt-artisan","commit_stats":{"total_commits":50,"total_committers":6,"mean_commits":8.333333333333334,"dds":0.48,"last_synced_commit":"8bf17fa40ba7b92ef3c77f1bc9761a26aeaa0cd5"},"previous_names":[],"tags_count":9,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/generationtux%2Fjwt-artisan","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/generationtux%2Fjwt-artisan/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/generationtux%2Fjwt-artisan/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/generationtux%2Fjwt-artisan/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/generationtux","download_url":"https://codeload.github.com/generationtux/jwt-artisan/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":247378149,"owners_count":20929297,"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":[],"created_at":"2024-08-02T08:01:05.622Z","updated_at":"2025-04-05T18:11:19.328Z","avatar_url":"https://github.com/generationtux.png","language":"PHP","funding_links":[],"categories":["PHP","Packages and Middleware"],"sub_categories":["Videos"],"readme":"# JWT Artisan\n\n![Build Test Status](https://github.com/generationtux/jwt-artisan/actions/workflows/test.yml/badge.svg?event=push)\n\n## Token auth for Laravel and Lumen web artisans\n\n[JWT](http://jwt.io/) is a great solution for authenticating API requests between various services. This package\nmakes working with JWT super easy for both [Laravel](http://laravel.com/) and [Lumen](http://lumen.laravel.com/).\n\n### Why JWT?\n\nBecause you have\n\n![microservices](http://i.imgur.com/GJlYD83.jpg)\n\nThat need to authenticate with each other so you can turn away bad requests like\n\n![how bout no](http://i.imgur.com/BMPy7AG.png)\n\nWhich is why JWT makes you feel like\n\n![yea baby](http://i.imgur.com/lySEl7O.jpg)\n\n### Contents\n\n- [Setup](#setup)\n- [Configure](#configure)\n- [Working with Tokens](#working-with-tokens)\n\n## Setup\n\nInstall the package using composer\n\n    $ composer require generationtux/jwt-artisan\n\nAdd the appropriate service provider for Laravel/Lumen\n\n```php\n// Laravel\n// config/app.php\n'providers' =\u003e [\n    ...\n    GenTux\\Jwt\\Support\\LaravelServiceProvider::class,\n]\n\n// Lumen\n// bootstrap/app.php\n$app-\u003eregister(GenTux\\Jwt\\Support\\LumenServiceProvider::class);\n```\n\n## Configure\n\nAll configuration for this package can be set using environment variables. The reason for using environment variables instead\nof config files is so that it can be integrated with both Laravel \u0026 Lumen as easily as possible. See the table below\nfor the available config options and their defaults.\n\n| Config       | Default         | Description                                                                                                                                                                             |\n| ------------ | --------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |\n| `JWT_SECRET` | _null_          | The secret key that will be used for sigining/validating tokens.                                                                                                                        |\n| `JWT_ALGO`   | _HS256_         | The algorithm to use for sigining tokens.                                                                                                                                               |\n| `JWT_LEEWAY` | _0_             | Seconds of leeway for validating timestamps to account for time differences between systems                                                                                             |\n| `JWT_INPUT`  | _token_         | By default we will look for the token in the `Authorization` header. If it's not found there, then this value will be used to search the sent input from the request to find the token. |\n| `JWT_HEADER` | _Authorization_ | By default the `Authorization` header key is used. This can be overridden with this value.                                                                                              |\n\nIf you're using the `JwtExceptionHandler` to handle exceptions, these environment variables can be set to customize the error messages.\n_(see below for information on using the exception handler)_\n\n| Config                 | Default                                                        | Description                                                                          |\n| ---------------------- | -------------------------------------------------------------- | ------------------------------------------------------------------------------------ |\n| `JWT_MESSAGE_ERROR`    | _There was an error while validating the authorization token._ | `500` A general error occured while working with the token.                          |\n| `JWT_MESSAGE_INVALID`  | _Authorization token is not valid._                            | `401` The provided token is invalid in some way: expired, mismatched signature, etc. |\n| `JWT_MESSAGE_NOTOKEN`  | _Authorization token is required._                             | `401` There was no token found with the request.                                     |\n| `JWT_MESSAGE_NOSECRET` | _No JWT secret defined._                                       | `500` Unable to find the JWT secret for validating/signing tokens.                   |\n\n## Working with Tokens\n\n- [Creating Tokens](#creating-tokens)\n- [Validating Tokens](#validating-tokens)\n- [Payloads](#payloads)\n- [Handling Errors](#handling-errors)\n\n### Creating Tokens\n\nInject an instance of `GenTux\\Jwt\\JwtToken` into your controller or other service to create new tokens.\n\n```php\n\u003c?php\n\nuse GenTux\\Jwt\\JwtToken;\n\nclass TokensController extends controller\n{\n        public function create(JwtToken $jwt)\n        {\n                $payload = [\"exp\" =\u003e time() + 7200]; // expire in 2 hours\n                $token = $jwt-\u003ecreateToken($payload); // new instance of JwtToken\n\n                return (string) $token;\n        }\n}\n```\n\nImplement `GenTux\\Jwt\\JwtPayloadInterface` to pass other objects to `createToken` for a more dynamic payload.\n\n```php\n\u003c?php\n\nuse GenTux\\Jwt\\JwtPayloadInterface;\n\nclass User extends Model implements JwtPayloadInterface\n{\n        public function getPayload()\n        {\n                return [\n                        \"sub\" =\u003e $this-\u003eid,\n                        \"exp\" =\u003e time() + 7200,\n                        \"context\" =\u003e [\n                                \"email\" =\u003e $this-\u003eemail,\n                        ],\n                ];\n        }\n}\n```\n\nThen simply pass that object when creating the token\n\n```php\n\u003c?php\n\nuse GenTux\\Jwt\\JwtToken;\n\nclass TokensController extends controller\n{\n        public function create(JwtToken $jwt)\n        {\n                $user = User::find(1);\n                $token = $jwt-\u003ecreateToken($user);\n\n                return $token-\u003epayload(); // ['sub' =\u003e 1, exp =\u003e '...', 'context' =\u003e ...]\n        }\n}\n```\n\nYou can set a specific `secret` and `algorithm` to use if necessary\n\n```php\npublic function create(JwtToken $jwt)\n{\n    return $jwt\n            -\u003esetSecret('secret_123')\n            -\u003esetAlgorithm('custom')\n            -\u003ecreateToken('[...]');\n}\n```\n\n### Validating Tokens\n\nThe easiest way to validate a request with a JWT token is to use the provided middleware.\n\n```php\n\u003c?php\n\n// Laravel\nRoute::group([\"middleware\" =\u003e \"jwt\"], function () {\n        Route::post(\"/foo\", \"FooController\");\n});\n\n// Lumen\n$app-\u003egroup(\n        [\"middleware\" =\u003e \"jwt\", \"namespace\" =\u003e \"App\\Http\\Controllers\"],\n        function ($app) {\n                $app-\u003epost(\"/foo\", \"FooController\");\n        }\n);\n```\n\nWhen a token is invalid, `GenTux\\Jwt\\Exceptions\\InvalidTokenException` will be thrown. If no token is provided,\nthen `GenTux\\Jwt\\Exceptions\\NoTokenException` will be thrown.\n\nTo manually validate the token, you can get tokens in any class using the trait `GenTux\\Jwt\\GetsJwtToken`.\n\nFor example, in a **Laravel** request object\n\n```php\n\u003c?php\n\nuse GenTux\\Jwt\\GetsJwtToken;\n\nclass CreateUser extends FormRequest\n{\n        use GetsJwtToken;\n\n        public function authorize()\n        {\n                return $this-\u003ejwtToken()-\u003evalidate();\n        }\n}\n```\n\nOr in a controller for **Lumen**\n\n```php\n\u003c?php\n\nuse GenTux\\Jwt\\GetsJwtController;\n\nclass FooController extends controller\n{\n    use GetsJwtToken;\n\n    public function store()\n    {\n        if( ! $this-\u003ejwtToken()-\u003evalidate()) {\n            return redirect('/nope');\n        }\n\n        ...\n    }\n}\n```\n\n### Payloads\n\nOnce you have the token, working with the payload is easy.\n\n```php\n\u003c?php\n\nuse GenTux\\Jwt\\GetsJwtToken;\n\nclass TokenService\n{\n        use GetsJwtToken;\n\n        public function getExpires()\n        {\n                $payload = $this-\u003ejwtPayload(); // shortcut for $this-\u003ejwtToken()-\u003epayload()\n\n                return $payload[\"exp\"];\n        }\n}\n```\n\nThe `payload` method for JwtToken accepts a `path` that can be used to get specific data from the payload.\n\n```php\n\u003c?php\n\nuse GenTux\\Jwt\\GetsJwtToken;\n\nclass TokenService\n{\n        use GetsJwtToken;\n\n        public function getData()\n        {\n                // ['exp' =\u003e '123', 'context' =\u003e ['foo' =\u003e 'bar']]\n\n                $token = $this-\u003ejwtToken();\n                $token-\u003epayload(\"exp\"); // 123\n                $token-\u003epayload(\"context.foo\"); // bar\n                $token-\u003epayload(\"context.baz\"); // null\n        }\n}\n```\n\n### Handling Errors\n\nThis package can handle JWT exceptions out of the box if you would like. It will take all JWT exceptions\nand return JSON error responses. If you would like to implements your own error handling, you can look\nat `GenTux\\Jwt\\Exceptions\\JwtExceptionHandler` for an example.\n\nTo implement, add the following inside of `app/Exceptions/Handler.php`\n\n```php\n\u003c?php\n\nuse GenTux\\Jwt\\Exceptions\\JwtException;\nuse GenTux\\Jwt\\Exceptions\\JwtExceptionHandler;\n\nclass Handler extends ExceptionHandler\n{\n    use JwtExceptionHandler;\n\n    public function render($request, Exception $e)\n    {\n        if($e instanceof JwtException) return $this-\u003ehandleJwtException($e);\n\n        ...\n    }\n}\n```\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fgenerationtux%2Fjwt-artisan","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fgenerationtux%2Fjwt-artisan","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fgenerationtux%2Fjwt-artisan/lists"}