Learn Laravel ยท 9/17

Authorization: Who Can Do What?

5 min read

๐Ÿ“œ Authorization: Who Can Do What?

Welcome, intrepid developer! So, you've mastered the art of letting users into your application with authentication. Now, it's time to lay down the law and define what they can actually do once they're inside. This is the realm of Authorization, and in Laravel, we have some fantastic tools to make this a breeze.

The Problem: Anarchy in Your Application! ๐Ÿ˜ฑ

Imagine you've built a bustling online marketplace. You have sellers, buyers, and administrators. Without authorization, a mischievous buyer could try to edit a seller's product listing, or a well-meaning seller might accidentally stumble into the super-secret admin dashboard. Chaos, right?

This is the problem authorization solves: it ensures users can only perform actions they are permitted to. It's the digital bouncer for your application's exclusive sections and features.

Laravel provides two primary ways to handle this: Gates and Policies. Think of them as two different security guards for your app. One is a quick and nimble guard for general-purpose checks (Gates), and the other is a highly specialized guard assigned to a specific area, like a museum exhibit (Policies).


๐Ÿšช Gates: Simple Closure-Based Permissions

Let's start with the simpler of the two: Gates. Gates are an excellent way to get started with authorization in Laravel. They are essentially closures that determine if a user has permission to perform a specific action. They are perfect for actions that aren't tied to a particular model or resource, like checking if a user can access the admin dashboard.

Defining a Gate

You'll typically define your Gates in the boot method of the app/Providers/AuthServiceProvider.php file. Let's create a Gate to check if a user is an administrator.

php
// app/Providers/AuthServiceProvider.php

use App\Models\User;
use Illuminate\Support\Facades\Gate;
use Illuminate\Foundation\Support\Providers\AuthServiceProvider as ServiceProvider;

class AuthServiceProvider extends ServiceProvider
{
    /**
     * The policy mappings for the application.
     *
     * @var array
     */
    protected $policies = [
        // 'App\Models\Model' => 'App\Policies\ModelPolicy',
    ];

    /**
     * Register any authentication / authorization services.
     *
     * @return void
     */
    public function boot()
    {
        $this->registerPolicies();

        Gate::define('view-dashboard', function (User $user) {
            return $user->isAdmin(); // Assuming you have an isAdmin() method on your User model
        });
    }
}

In this example, we've defined a Gate named view-dashboard. This Gate receives the currently authenticated user and returns true if they are an admin, and false otherwise.

Authorizing Actions with Gates

Now that we've defined our Gate, how do we use it? Laravel provides a few convenient ways.

In a Controller:

You can use the Gate facade's allows or denies methods.

php
// app/Http/Controllers/DashboardController.php

use Illuminate\Support\Facades\Gate;

class DashboardController extends Controller
{
    public function index()
    {
        if (Gate::denies('view-dashboard')) {
            abort(403); // Forbidden
        }

        return view('dashboard');
    }
}

If the user is not authorized, we're throwing a 403 error, which is the standard "Forbidden" HTTP response.

A Fun Fact: The HTTP status code 403 Forbidden is like a bouncer at a club telling you, "I know who you are, but you're still not getting in." It's different from a 401 Unauthorized, which is more like the bouncer saying, "I don't even know who you are."


๐Ÿ‘ฎ Policies: Organizing Authorization Around Models

Gates are great for simple checks, but what if your authorization logic is more complex or tied to a specific model? For instance, can a user update a blog post? This depends on whether they are the author of that post. This is where Policies shine.

Policies are classes that group authorization logic for a particular model or resource. This keeps your authorization rules neat and tidy.

Generating a Policy

You can easily generate a policy using an Artisan command:

bash
php artisan make:policy PostPolicy --model=Post

This will create a PostPolicy.php file in the app/Policies directory and will pre-fill it with methods for common actions like view, create, update, and delete.

Registering a Policy

Once you've created a policy, you need to register it in your AuthServiceProvider.

php
// app/Providers/AuthServiceProvider.php

use App\Models\Post;
use App\Policies\PostPolicy;

protected $policies = [
    Post::class => PostPolicy::class,
];

This tells Laravel to use the PostPolicy whenever it needs to authorize actions on a Post model.

Writing Policy Methods

Let's implement the update method in our PostPolicy to allow a user to update a post only if they are the author.

php
// app/Policies/PostPolicy.php

namespace App\Policies;

use App\Models\Post;
use App\Models\User;
use Illuminate\Auth\Access\HandlesAuthorization;

class PostPolicy
{
    use HandlesAuthorization;

    /**
     * Determine whether the user can update the model.
     *
     * @param  \App\Models\User  $user
     * @param  \App\Models\Post  $post
     * @return \Illuminate\Auth\Access\Response|bool
     */
    public function update(User $user, Post $post)
    {
        return $user->id === $post->user_id;
    }
}

๐Ÿ›ก๏ธ Authorizing Actions in Controllers and Blade Views

Now for the grand finale! Let's put our shiny new policy to work in our controllers and Blade views.

In Controllers

Laravel provides a handy authorize method in your base controller.

php
// app/Http/Controllers/PostController.php

use App\Models\Post;
use Illuminate\Http\Request;

class PostController extends Controller
{
    public function update(Request $request, Post $post)
    {
        $this->authorize('update', $post);

        // The current user can update the post...

        $post->update($request->all());

        return redirect()->route('posts.show', $post);
    }
}

The authorize method will automatically use the PostPolicy's update method. If the authorization fails, it will throw an AuthorizationException, which results in a 403 HTTP response. It's clean, expressive, and keeps your controller focused on its main job.

For resource controllers, you can even authorize all actions at once in the constructor, which is incredibly efficient.

php
public function __construct()
{
    $this->authorizeResource(Post::class, 'post');
}

In Blade Views

You often need to show or hide parts of your UI based on a user's permissions. Laravel's Blade templating engine provides some elegant directives for this.

The @can and @cannot directives are your best friends here.

blade
{{-- In your posts/show.blade.php view --}}

@can('update', $post)
    <a href="{{ route('posts.edit', $post) }}">Edit Post</a>
@endcan

@can('delete', $post)
    <form method="POST" action="{{ route('posts.destroy', $post) }}">
        @csrf
        @method('DELETE')
        <button type="submit">Delete Post</button>
    </form>
@endcan

This ensures that only authorized users will even see the "Edit" and "Delete" buttons, creating a more secure and user-friendly experience.

There's also a handy @canany directive to check for multiple permissions at once.

blade
@canany(['update', 'delete'], $post)
    <!-- The user can update or delete the post -->
@endcanany

By mastering Gates and Policies, you'll be able to build robust and secure Laravel applications where everyone knows their place and plays by the rules. Happy coding! ๐Ÿ‘จโ€๐Ÿ’ป


๐Ÿ“š Further Reading

Challenge

You are building the authorization layer for an e-commerce platform. You have three user roles: 'admin', 'seller', and 'buyer'. Your task is to implement authorization logic using Laravel's Gates and Policies.

Scenario:

  • Models: User, Product. A Product belongs to a Store, and a User (if they are a 'seller') also belongs to a Store. We will simulate this by checking a store_id property on both the user and product objects.
  • User Properties: A User object has a role property ('admin', 'seller', or 'buyer') and a store_id property.
  • Product Properties: A Product object has a store_id property.

Your Tasks:

  1. In AuthServiceProvider.php:

    • Define a Gate named view-admin-panel. This gate should only grant access to users with the role of 'admin'.
    • Register the ProductPolicy to be used for the Product model.
  2. In ProductPolicy.php:

    • Implement the update method. Authorization should be granted if the user is an 'admin' OR if the user is a 'seller' whose store_id matches the product's store_id.
  3. In ProductController.php:

    • Inside the update method, add the necessary line of code to authorize the 'update' action for the given $product using its policy.
  4. In products/show.blade.php:

    • Use the appropriate Blade authorization directive to ensure that the <a> tag for "Edit Product" is only rendered if the current user is authorized to 'update' the $product.

Expected result

app/Providers/AuthServiceProvider.php

The policies array should map the Product model to the ProductPolicy. The boot method should contain the Gate definition, checking if the user's role is 'admin'.

php
protected $policies = [
    Product::class => ProductPolicy::class,
];

public function boot()
{
    $this->registerPolicies();

    Gate::define('view-admin-panel', function ($user) {
        return $user->role === 'admin';
    });
}

app/Policies/ProductPolicy.php

The update method should return true if the user is an admin or if the user is a seller who owns the product's store.

php
public function update(User $user, Product $product)
{
    return $user->role === 'admin' || ($user->role === 'seller' && $user->store_id === $product->store_id);
}

app/Http/Controllers/ProductController.php

The update method should call $this->authorize() to check the 'update' ability on the given $product before any other logic is executed.

php
public function update(Request $request, Product $product)
{
    $this->authorize('update', $product);
    
    // ... logic to update the product would follow
    return response('Product updated.');
}

resources/views/products/show.blade.php

The link should be wrapped in a @can directive, checking if the authenticated user can 'update' the $product instance.

blade
@can('update', $product)
    <a href="/products/{{ $product->id }}/edit">Edit Product</a>
@endcan
php

Solve the challenge, then check it.

Ctrl+Enter

Course complete!

You've passed every challenge in this course.