Home>Article>PHP Framework> Let’s talk about interceptors (Gates) in Laravel

Let’s talk about interceptors (Gates) in Laravel

青灯夜游
青灯夜游 forward
2022-09-28 19:59:34 1606browse

Let’s talk about interceptors (Gates) in Laravel

Laravel Gates (interceptors) allow you to authorize users to access certain areas of your application. You can easily define interceptors in your application and then use them to allow or deny access.

Simple example

Suppose in the user table, there is a column namedadmin, depending on whether the user is an administrator, it can be1or0. We can easily secure a module that is part of the application with a simple check like this:

Route::get('administration', function(){ if(auth()->check() && auth()->user()->admin){ echo 'Welcome to the admin section'; } else { echo 'You shall not pass'; } });

If a specific user has theiradminline set to1, they will see the following output.

Admin access screenshot

Otherwise, they will see the following:

Admin denied access

This looks great right! We have an easy way to allow or deny access to specific parts of our application. However, the problem is: what if there are a large number of places throughout the application where user access permissions need to be checked and modified. We would have to search the code globally and modify this logic everywhere. Not very efficient.

For this, we can define a Gate (interceptor) and use it throughout the application.

Define the interceptor

To define the interceptor, you can open theApp\Providers\AuthServiceProvider.phpfile and in ourboot ()Add the following content to the method:

public function boot() { $this->registerPolicies(); Gate::define('access-admin', function ($user) { return $user->admin; }); }

We can use this interceptor anywhere in the entire application where we want to authenticate the administrator user. In the next section you'll see how we use this new interceptor.

Using interceptors

To use interceptors, we can callGate::allows()orGate::denies( )method, as shown below:

Route::get('administration', function(){ if (Gate::allows('access-admin')) { echo 'Welcome to the admin section'; } else { echo 'You shall not pass'; } });

Please note:Gate::denies()method will doGate::allows()The benefit of performing a reverse check

interceptor is that we can now change our definition at any time and the authorization logic will be changed synchronously throughout the application.

Another purpose of using interceptors is to check permissions related to data. Taking a blog as an example, we can grant users editing permissions on posts they create.

We can pass data to the interceptor to check if the user has permission to perform an action.

Passing data like an interceptor

Suppose our application has aPosttable with a columnuser_id, It contains theIDof the user who created it. We can define a Gate (interceptor) to determine if a user can edit a specific post like this:

Gate::define('edit-post', function ($user, $post) { return $user->id === $post->user_id; });

Two parameters are passed to our interceptor definition. The first is the$userobject, which contains the authenticated user, and the second parameter is our$postobject.

Tips: If there is no authenticated user, the interceptor will return false.

The interceptor will allow access if the authenticated user is the original author; otherwise it will deny access.

Here's a quick example of how we can use the newedit-postinterceptor.

Route::get('edit/{id}', function($id){ $post = \App\Model\Post::find($id); if( Gate::allows('edit-post', $post) ){ echo 'You can edit this post'; } else { echo 'You shall not pass'; } });

Above, we usedRoute Closuresin the example, but we may want to map this route to a controller. This will also let us use the newAuthorizefunction.

Authorize Authorization Helper Function

In addition to efficiency, another reason to use interceptors is the helper function.

Assume we map the route to the controller:

Route::get('edit/{id}', 'PostController@edit');

We can use theauthorize()helper to check if the authenticated user has permission to edit the post:

authorize('edit-post', $post); } }

If the controller inherits from theApp\Http\Controllers\Controllerbase class, you can use thefunction just like theGate::allow()function authorize()Helper function.

Finally, what if we want to check authorization in the view? We can do this using the@canBlade function helper.

Authentication at the view layer

Assume that the Blade view is as follows:

nbsp;html>   {{ $post->title }} 

{{ $post->title }}

{!! $post->body !!}

We can use the Blade helper function@canCheck if the current user is allowed to edit this post:

nbsp;html>   {{ $post->title }} 

{{ $post->title }}

{!! $post->body !!}

@can('edit-post', $post)id }}">Edit Post@endcan

If the authenticated user is the original author of the post, they will see anEdit Postbutton.

Using the@canhelper function can make our code easier to read and manage. You can also use@cannotto reverse the operation.

Summary

This is the basics of using Gates (interceptors) in Laravel applications. Interceptors allow us to easily authorize specific users to access areas of our application. This may also be called an Access Control List (ACL), a list of permissions associated with an object.

But we shouldn't overcomplicate things... In the simplest scenario,Interceptorsare used to allow or deny access. Users can either be allowed authorization or be denied authorization.

Since this tutorial is about getting the user through and not through... it makes sense to send you out with this image of Gandalf from Lord of the Rings (manual dog head).

Let’s talk about interceptors (Gates) in Laravel

To learn more about Laravel Gates (interceptors), be sure to visit the Larav authorization documentation.

English original address: https://devdojo.com/tnylea/laravel-gates

Translation address: https://learnku.com/laravel/t/67585

[Related recommendations:laravel video tutorial]

The above is the detailed content of Let’s talk about interceptors (Gates) in Laravel. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:learnku.com. If there is any infringement, please contact admin@php.cn delete