{"id":19324873,"url":"https://github.com/spatie/laravel-authorize","last_synced_at":"2025-04-05T05:06:45.170Z","repository":{"id":43060606,"uuid":"42896120","full_name":"spatie/laravel-authorize","owner":"spatie","description":"A middleware to check authorization","archived":false,"fork":false,"pushed_at":"2022-03-21T13:03:48.000Z","size":70,"stargazers_count":198,"open_issues_count":0,"forks_count":20,"subscribers_count":7,"default_branch":"master","last_synced_at":"2025-03-29T04:07:56.297Z","etag":null,"topics":["authorization","laravel","middleware","php","security"],"latest_commit_sha":null,"homepage":"https://murze.be/2015/09/a-middleware-to-check-abilities-on-the-route-level/","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/spatie.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}},"created_at":"2015-09-21T22:01:36.000Z","updated_at":"2024-09-10T21:28:41.000Z","dependencies_parsed_at":"2022-09-10T12:41:08.809Z","dependency_job_id":null,"html_url":"https://github.com/spatie/laravel-authorize","commit_stats":null,"previous_names":[],"tags_count":6,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/spatie%2Flaravel-authorize","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/spatie%2Flaravel-authorize/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/spatie%2Flaravel-authorize/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/spatie%2Flaravel-authorize/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/spatie","download_url":"https://codeload.github.com/spatie/laravel-authorize/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":247289428,"owners_count":20914464,"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":["authorization","laravel","middleware","php","security"],"created_at":"2024-11-10T02:07:18.570Z","updated_at":"2025-04-05T05:06:45.133Z","avatar_url":"https://github.com/spatie.png","language":"PHP","funding_links":[],"categories":[],"sub_categories":[],"readme":"\n[\u003cimg src=\"https://github-ads.s3.eu-central-1.amazonaws.com/support-ukraine.svg?t=1\" /\u003e](https://supportukrainenow.org)\n\n# A middleware to check authorization\n\n[![Latest Version on Packagist](https://img.shields.io/packagist/v/spatie/laravel-authorize.svg?style=flat-square)](https://packagist.org/packages/spatie/laravel-authorize)\n[![Software License](https://img.shields.io/badge/license-MIT-brightgreen.svg?style=flat-square)](LICENSE.md)\n[![Build Status](https://img.shields.io/travis/spatie/laravel-authorize/master.svg?style=flat-square)](https://travis-ci.org/spatie/laravel-authorize)\n[![SensioLabsInsight](https://img.shields.io/sensiolabs/i/c6adf478-99b9-4a52-8635-881f6b66c8d3.svg?style=flat-square)](https://insight.sensiolabs.com/projects/c6adf478-99b9-4a52-8635-881f6b66c8d3)\n[![Quality Score](https://img.shields.io/scrutinizer/g/spatie/laravel-authorize.svg?style=flat-square)](https://scrutinizer-ci.com/g/spatie/laravel-authorize)\n[![StyleCI](https://styleci.io/repos/42896120/shield?branch=master)](https://styleci.io/repos/42896120)\n[![Total Downloads](https://img.shields.io/packagist/dt/spatie/laravel-authorize.svg?style=flat-square)](https://packagist.org/packages/spatie/laravel-authorize)\n\nThis package provides a route middleware to protect routes from unauthorized access. It hooks into the authorization\nfeatures that were [introduced in Laravel 5.1.11](http://laravel.com/docs/5.1/authorization).\n\nProtecting a route can be done by adding middleware to it:\n```php\nRoute::get('/top-secret-page', [\n   'middleware' =\u003e 'can:viewTopSecretPage',\n   'uses' =\u003e 'TopSecretController@index',\n]);\n```\n\nOf course this middleware can also be applied to a bunch of routes:\n\n```php\nRoute::group(['prefix' =\u003e 'admin', 'middleware' =\u003e 'can:viewAdmin'], function() {\n\n   //all the controllers of your admin section\n   ...\n   \n});\n```\n\nFurthermore the middleware can use [route model binding](https://laracasts.com/series/laravel-5-fundamentals/episodes/18):\n```php\nRoute::get('/post/{post}', [\n   'middleware' =\u003e 'can:editPost,post',\n   'uses' =\u003e 'PostController@edit',\n]);\n```\n\nSpatie is a webdesign agency in Antwerp, Belgium. You'll find an overview of all our open source projects [on our website](https://spatie.be/opensource).\n\n## Support us\n\n[\u003cimg src=\"https://github-ads.s3.eu-central-1.amazonaws.com/laravel-authorize.jpg?t=1\" width=\"419px\" /\u003e](https://spatie.be/github-ad-click/laravel-authorize)\n\nWe invest a lot of resources into creating [best in class open source packages](https://spatie.be/open-source). You can support us by [buying one of our paid products](https://spatie.be/open-source/support-us).\n\nWe highly appreciate you sending us a postcard from your hometown, mentioning which of our package(s) you are using. You'll find our address on [our contact page](https://spatie.be/about-us). We publish all received postcards on [our virtual postcard wall](https://spatie.be/open-source/postcards).\n\n## Postcardware\n\nYou're free to use this package (it's [MIT-licensed](LICENSE.md)), but if it makes it to your production environment you are required to send us a postcard from your hometown, mentioning which of our package(s) you are using.\n\nOur address is: Spatie, Kruikstraat 22, 2018 Antwerp, Belgium.\n\nThe best postcards will get published on the open source page on our website.\n\n## Do not use in Laravel 5.2.28 and up\n\nLaravel 5.2.28 or higher contain the middleware this package provides [out of the box](https://github.com/laravel/framework/blob/v5.2.28/src/Illuminate/Foundation/Http/Middleware/Authorize.php). There's no need do install this package in those versions of Laravel. \n\n## Install\n\nYou can install the package via composer:\n``` bash\n$ composer require spatie/laravel-authorize\n```\n\nNext, you must install the service provider:\n\n```php\n// config/app.php\n'providers' =\u003e [\n    ...\n    Spatie\\Authorize\\AuthorizeServiceProvider::class,\n];\n```\n\nNext, the `\\Spatie\\Authorize\\Middleware\\Authorize::class`-middleware must be registered in the kernel:\n\n```php\n//app/Http/Kernel.php\n\nprotected $routeMiddleware = [\n  ...\n  'can' =\u003e \\Spatie\\Authorize\\Middleware\\Authorize::class,\n];\n```\n\nNaming the middleware `can` is just a suggestion. You can give it any name you'd like.\n\nThe `authorize`-middleware includes all functionality provided by the standard `auth`-middleware. So you could\nalso opt to replace the `App\\Http\\Middleware\\Authenticate`-middleware by `Spatie\\Authorize\\Middleware\\Authorize`:\n\n```php\n//app/Http/Kernel.php\n\nprotected $routeMiddleware = [\n    'auth' =\u003e 'Spatie\\Authorize\\Middleware\\Authorize',\n    ...\n];\n```\n\nYou can publish the config-file with:\n```bash\nphp artisan vendor:publish --provider=\"Spatie\\Authorize\\AuthorizeServiceProvider\"\n```\n\nThis is the contents of the published config file:\n\n```php\nreturn [\n    /*\n     * The path to redirect for login.\n     */\n    'login_url' =\u003e 'auth/login'\n];\n```\n\n## Usage\n\n### Checking authentication\nWhen the middleware is used without any parameters at all, it will only allow logged in users to use the route.\nIf you plan on using the middleware like this I recommend that you replace the standard `auth`-middleware with the one\nprovided by this package. \n\n```php\n//only logged in users will be able to see this\n\nRoute::get('/top-secret-page', ['middleware' =\u003e 'auth', 'uses' =\u003e 'TopSecretController@index']);\n```\n\n### Checking authorization\nThe middleware accepts the name of an ability you have defined as the first parameter:\n\n```php\n//only users with the viewTopSecretPage-ability be able to see this\n\nRoute::get('/top-secret-page', [\n   'middleware' =\u003e 'can:viewTopSecretPage',\n   'uses' =\u003e 'TopSecretController@index',\n]);\n```\n\n### Using form model binding\nImage you've set up an ability like this:\n\n```php\n//inside the boot method of AuthServiceProvider\n\n$gate-\u003edefine('update-post', function ($user, $post) {\n    return $user-\u003eid === $post-\u003euser_id;\n});\n```\n\nThe middleware accepts the name of a bound model as the second parameter.\n\n```php\nRoute::get('/post/{post}', [\n   'middleware' =\u003e 'can:editPost,post',\n   'uses' =\u003e 'PostController@edit',\n]);\n```\n\nBehind the scene the middleware will pass the model bound that is bound to the round to\nthe defined `update-post`-ability.\n\n## What happens with unauthorized requests?\n\n### Default behaviour\n\nThis is the default behaviour defined in the middleware.\n\n```php\nuse Symfony\\Component\\HttpKernel\\Exception\\HttpException;\n...\n\nprotected function handleUnauthorizedRequest($request, $ability = null, $model = null)\n{\n    if ($request-\u003eajax()) {\n        return response('Unauthorized.', Response::HTTP_UNAUTHORIZED);\n    }\n\n    if (!$request-\u003euser()) {\n        return redirect()-\u003eguest(config('laravel-authorize.login_url'));\n    }\n\n    throw new HttpException(Response::HTTP_UNAUTHORIZED, 'This action is unauthorized.');\n}\n```\n\nSo guests will get redirected to the default login page, logged in users will get a response\nwith status `HTTP_UNAUTHORIZED` aka 401.\n\n### Custom behaviour\n\nTo customize the default behaviour you can easily extend the default middleware and\noverride the `handleUnauthorizedRequest`-method. Don't forget to register your class at the kernel.\n\nIf you would like to let all unauthorized users know that you are actually a teapot you can do so.\n\n```php\n//app/Http/Middleware/Authorize.php\n\nnamespace App\\Http\\Middleware;\n\nuse Spatie\\Authorize\\Middleware\\Authorize as BaseAuthorize;\nuse Symfony\\Component\\HttpFoundation\\Response;\n\nclass Authorize extends BaseAuthorize\n{\n    protected function handleUnauthorizedRequest($request, $ability = null, $model = null)\n    {\n        return reponse('I am a teapot.', Response::HTTP_I_AM_A_TEAPOT);\n    }\n}\n```\n\nIn the kernel:\n\n```php\n//app/Http/Kernel.php\n\n  protected $routeMiddleware = [\n        'can' =\u003e 'App\\Http\\Middleware\\Authorize',\n        ...\n    ];\n```\n\n## Change log\n\nPlease see [CHANGELOG](CHANGELOG.md) for more information what has changed recently.\n\n## Testing\n\nThis package contains integration tests that are powered by [orchestral/testbench](https://github.com/orchestral/testbench).\n\nYou can run all tests with:\n``` bash\n$ composer test\n```\n\n## Contributing\n\nPlease see [CONTRIBUTING](https://github.com/spatie/.github/blob/main/CONTRIBUTING.md) for details.\n\n## Security\n\nIf you've found a bug regarding security please mail [security@spatie.be](mailto:security@spatie.be) instead of using the issue tracker.\n\n## Credits\n\n- [Freek Van der Herten](https://github.com/freekmurze)\n- [All Contributors](../../contributors)\n\nA big thank you to [Joseph Silber](https://github.com/JosephSilber) for all the excellent feedback he gave\nwhile this package was being created.\n\n## About Spatie\nSpatie is webdesign agency in Antwerp, Belgium. You'll find an overview of all our open source projects [on our website](https://spatie.be/opensource).\n\n## License\n\nThe MIT License (MIT). Please see [License File](LICENSE.md) for more information.\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fspatie%2Flaravel-authorize","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fspatie%2Flaravel-authorize","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fspatie%2Flaravel-authorize/lists"}