All Projects → spatie → Laravel Authorize

spatie / Laravel Authorize

Licence: mit
A middleware to check authorization

Projects that are alternatives of or similar to Laravel Authorize

Laravel Authz
An authorization library that supports access control models like ACL, RBAC, ABAC in Laravel.
Stars: ✭ 136 (-24.02%)
Mutual labels:  middleware, laravel, authorization
Roles Permissions Laravel
Roles and Permissions implementation on Laravel 5.4
Stars: ✭ 121 (-32.4%)
Mutual labels:  laravel, authorization
Sentinel
A framework agnostic authentication & authorization system.
Stars: ✭ 1,354 (+656.42%)
Mutual labels:  laravel, authorization
Laravel Governor
Manage authorization with granular role-based permissions in your Laravel Apps.
Stars: ✭ 131 (-26.82%)
Mutual labels:  laravel, authorization
Laravel Analytics
Analytics for the Laravel framework.
Stars: ✭ 91 (-49.16%)
Mutual labels:  middleware, laravel
Depictr
A middleware for rendering static pages when crawled by search engines
Stars: ✭ 92 (-48.6%)
Mutual labels:  middleware, laravel
Laravel Auth
A powerful authentication, authorization and verification package built on top of Laravel. It provides developers with Role Based Access Control, Two-Factor Authentication, Social Authentication, and much more, compatible Laravel’s standard API and fully featured out of the box.
Stars: ✭ 128 (-28.49%)
Mutual labels:  laravel, authorization
Laravel5.7 Vue Cli3 Boilerplate
Boilerplate / Starter kit. Laravel 5.7, Vue CLI 3 — Authentication with Email Verification. REST API.
Stars: ✭ 52 (-70.95%)
Mutual labels:  laravel, authorization
Has Parameters
A trait that allows you to pass arguments to Laravel middleware in a more PHP'ish way.
Stars: ✭ 149 (-16.76%)
Mutual labels:  middleware, laravel
Request Migrations
HTTP Request Migrations for API Versioning like Stripe
Stars: ✭ 149 (-16.76%)
Mutual labels:  middleware, laravel
Go Web
A new Golang MVC Framework. Like Laravel... but faster!
Stars: ✭ 79 (-55.87%)
Mutual labels:  middleware, laravel
Laravel Rate Limited Job Middleware
A job middleware to rate limit jobs
Stars: ✭ 166 (-7.26%)
Mutual labels:  middleware, laravel
Brandenburg
Laravel Authentication Package
Stars: ✭ 79 (-55.87%)
Mutual labels:  laravel, authorization
Laravel Localize Middleware
Configurable localization middleware for your Laravel >=5.1 application
Stars: ✭ 92 (-48.6%)
Mutual labels:  middleware, laravel
Laravel Remember Uploads
Laravel Middleware and helper for remembering file uploads during validation redirects
Stars: ✭ 67 (-62.57%)
Mutual labels:  middleware, laravel
L5 Very Basic Auth
Stateless HTTP basic auth for Laravel without the need for a database.
Stars: ✭ 127 (-29.05%)
Mutual labels:  middleware, laravel
Egg Authz
egg-authz is an authorization middleware for Egg.js based on Casbin
Stars: ✭ 50 (-72.07%)
Mutual labels:  middleware, authorization
Authorization
PSR7 Middleware for authorization
Stars: ✭ 50 (-72.07%)
Mutual labels:  middleware, authorization
Laratrust
Handle roles and permissions in your Laravel application
Stars: ✭ 1,799 (+905.03%)
Mutual labels:  laravel, authorization
Negroni Authz
negroni-authz is an authorization middleware for Negroni
Stars: ✭ 152 (-15.08%)
Mutual labels:  middleware, authorization

A middleware to check authorization

Latest Version on Packagist Software License Build Status SensioLabsInsight Quality Score StyleCI Total Downloads

This package provides a route middleware to protect routes from unauthorized access. It hooks into the authorization features that were introduced in Laravel 5.1.11.

Protecting a route can be done by adding middleware to it:

Route::get('/top-secret-page', [
   'middleware' => 'can:viewTopSecretPage',
   'uses' => '[email protected]',
]);

Of course this middleware can also be applied to a bunch of routes:

Route::group(['prefix' => 'admin', 'middleware' => 'can:viewAdmin'], function() {

   //all the controllers of your admin section
   ...
   
});

Furthermore the middleware can use route model binding:

Route::get('/post/{post}', [
   'middleware' => 'can:editPost,post',
   'uses' => '[email protected]',
]);

Spatie is a webdesign agency in Antwerp, Belgium. You'll find an overview of all our open source projects on our website.

Support us

We invest a lot of resources into creating best in class open source packages. You can support us by buying one of our paid products.

We 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. We publish all received postcards on our virtual postcard wall.

Postcardware

You're free to use this package (it's MIT-licensed), 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.

Our address is: Spatie, Kruikstraat 22, 2018 Antwerp, Belgium.

The best postcards will get published on the open source page on our website.

Do not use in Laravel 5.2.28 and up

Laravel 5.2.28 or higher contain the middleware this package provides out of the box. There's no need do install this package in those versions of Laravel.

Install

You can install the package via composer:

$ composer require spatie/laravel-authorize

Next, you must install the service provider:

// config/app.php
'providers' => [
    ...
    Spatie\Authorize\AuthorizeServiceProvider::class,
];

Next, the \Spatie\Authorize\Middleware\Authorize::class-middleware must be registered in the kernel:

//app/Http/Kernel.php

protected $routeMiddleware = [
  ...
  'can' => \Spatie\Authorize\Middleware\Authorize::class,
];

Naming the middleware can is just a suggestion. You can give it any name you'd like.

The authorize-middleware includes all functionality provided by the standard auth-middleware. So you could also opt to replace the App\Http\Middleware\Authenticate-middleware by Spatie\Authorize\Middleware\Authorize:

//app/Http/Kernel.php

protected $routeMiddleware = [
    'auth' => 'Spatie\Authorize\Middleware\Authorize',
    ...
];

You can publish the config-file with:

php artisan vendor:publish --provider="Spatie\Authorize\AuthorizeServiceProvider"

This is the contents of the published config file:

return [
    /*
     * The path to redirect for login.
     */
    'login_url' => 'auth/login'
];

Usage

Checking authentication

When the middleware is used without any parameters at all, it will only allow logged in users to use the route. If you plan on using the middleware like this I recommend that you replace the standard auth-middleware with the one provided by this package.

//only logged in users will be able to see this

Route::get('/top-secret-page', ['middleware' => 'auth', 'uses' => '[email protected]']);

Checking authorization

The middleware accepts the name of an ability you have defined as the first parameter:

//only users with the viewTopSecretPage-ability be able to see this

Route::get('/top-secret-page', [
   'middleware' => 'can:viewTopSecretPage',
   'uses' => '[email protected]',
]);

Using form model binding

Image you've set up an ability like this:

//inside the boot method of AuthServiceProvider

$gate->define('update-post', function ($user, $post) {
    return $user->id === $post->user_id;
});

The middleware accepts the name of a bound model as the second parameter.

Route::get('/post/{post}', [
   'middleware' => 'can:editPost,post',
   'uses' => '[email protected]',
]);

Behind the scene the middleware will pass the model bound that is bound to the round to the defined update-post-ability.

What happens with unauthorized requests?

Default behaviour

This is the default behaviour defined in the middleware.

use Symfony\Component\HttpKernel\Exception\HttpException;
...

protected function handleUnauthorizedRequest($request, $ability = null, $model = null)
{
    if ($request->ajax()) {
        return response('Unauthorized.', Response::HTTP_UNAUTHORIZED);
    }

    if (!$request->user()) {
        return redirect()->guest(config('laravel-authorize.login_url'));
    }

    throw new HttpException(Response::HTTP_UNAUTHORIZED, 'This action is unauthorized.');
}

So guests will get redirected to the default login page, logged in users will get a response with status HTTP_UNAUTHORIZED aka 401.

Custom behaviour

To customize the default behaviour you can easily extend the default middleware and override the handleUnauthorizedRequest-method. Don't forget to register your class at the kernel.

If you would like to let all unauthorized users know that you are actually a teapot you can do so.

//app/Http/Middleware/Authorize.php

namespace App\Http\Middleware;

use Spatie\Authorize\Middleware\Authorize as BaseAuthorize;
use Symfony\Component\HttpFoundation\Response;

class Authorize extends BaseAuthorize
{
    protected function handleUnauthorizedRequest($request, $ability = null, $model = null)
    {
        return reponse('I am a teapot.', Response::HTTP_I_AM_A_TEAPOT);
    }
}

In the kernel:

//app/Http/Kernel.php

  protected $routeMiddleware = [
        'can' => 'App\Http\Middleware\Authorize',
        ...
    ];

Change log

Please see CHANGELOG for more information what has changed recently.

Testing

This package contains integration tests that are powered by orchestral/testbench.

You can run all tests with:

$ composer test

Contributing

Please see CONTRIBUTING for details.

Security

If you discover any security related issues, please email [email protected] instead of using the issue tracker.

Credits

A big thank you to Joseph Silber for all the excellent feedback he gave while this package was being created.

About Spatie

Spatie is webdesign agency in Antwerp, Belgium. You'll find an overview of all our open source projects on our website.

License

The MIT License (MIT). Please see License File for more information.

Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].