Laravel basic tutorial-authorization

Source: Internet
Author: User
Tags laravel tutorial
Basic laravel tutorial-authorization overview

Laravel not only provides out-of-the-box authorization services, but also provides many simple ways to manage authorization logic and resource access control. These methods and help functions help you manage your authorization logic. We will give a one-to-one explanation in this chapter.

Definition capability

The simplest way to determine whether a user can execute a given action is to use the Illuminate \ Auth \ Access \ Gate class to define the corresponding capabilities. The AuthServiceProvider class provided by laravel is the recommended location for defining these capabilities. Let's look at an example. we define an update-post capability that receives a current User and a Post model. In this capability, we need to determine whether the user id matches the post user_id:

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

Note that the preceding example does not check whether the given $ user is NULL. This is because when a given user is not authenticated or the user is not specified by the forUser method, the Gate class automatically returns false for all capabilities.

Class-based capabilities

In addition to using Closures as the authorization check callback to register capabilities, you can also register capabilities by passing methods in the class. when necessary, class will be parsed through the service container:

$gate->define('update-post', 'Class@method');

Authorization check interceptor

Sometimes, you may need to issue a pass for all capabilities to some special users. in this case, you can use the before method to define a callback, which will run before all authorization checks:

$gate->before(function ($user, $ability) {  if ($user->isSuperAdmin()) {    return true;  }});

If the before callback function returns a non-empty result, the result will be used as the check result.

You can also use the after method to define a callback function executed after each capability authorization check. However, you cannot modify the check result in this callback function:

$gate->after(function ($user, $ability, $result, $arguments) {  //});
Check capability through Gate mask

Once a capability is defined, we can check the capability in multiple ways. First, we can use the check, allows, or denies method of the Gate mask. All these methods receive the name of the capability and pass the additional parameters to the callback function of the corresponding capability. You do not need to pass the current user to these methods. Gate will automatically forward the current user to the parameter and pass it to the callback function of the capability. So when we check the previously defined update-post capability, we only need to pass the Post instance to the denies method:

    

Of course, the allows method is opposite to the denies method. if the action is authorized to pass, true is returned. the check method is the alias of the allows method.

Checks the specified user

If you want to use the Gate mask to check whether other users that are not currently authorized to pass the user have the corresponding capabilities, you can use the forUser method:

if (Gate::forUser($user)->allows('update-post', $post)) {  //}

Pass multiple parameters

Of course, the ability callback function can receive multiple parameters:

Gate:define('delete-comment', function ($user, $post, $comment) {  // });

If your capabilities need to receive multiple parameters, you can simply pass an array composed of multiple parameters through the Gate mask method:

if (Gate::allows('delete-comment', [$post, $comment])) {  //}
Pass user model check capability

In fact, you can check the User's capabilities through the instance of the User model. The default laravel App \ User model uses Authorizable trait, which contains two methods: can and cannot. The two methods have the same usage as the allows and denies methods of the Gate mask. We also use the previous example and modify it to the following:

  user()->cannot('update-post', $post)) {       abort(403);     }     // Update Post...   }}

Of course, the can Method is opposite to cannot:

if ($request->user()->can('update-post', $post)) {  // Update Post...}
Check the capabilities in the Blade Template

For convenience, laravel provides the @ can Blade command to quickly check whether the authorized user has the specified capability. For example:

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

You can also use the @ else command with the @ can command:

@can('update-post', $post)  
  @else  
  @endcan
Check the capability in form requests

You can also use the custom authoriza method of form requests (inherited from the Request for form verification) to verify the capabilities defined in the Gate mask:

/** * Determine if the user is authorized to make this request. * * @return bool */ public function authorize() {   $postId = $this->route('post');   return Cate::allows('update', Post::findOrFail($postId)); }
Policies

In order to prevent you from putting all the authorization logic into AuthServiceProvider, the application grows into a huge and cumbersome application. Laravel allows you to use the Policy class to separate your authorization logic. The policy class is actually a native PHP class containing the authorization Logic Group.

First, let's generate a policy to manage our Post authorization. You can use the make: policy command to generate a policy. The generated policy is stored in the app/Policies Directory:

php artisan make:policy PostPolicy

Registration Policy

Once the policy exists, we also need to register it in the Gate class. The AuthServiceProvider contains the policies attribute, which stores mappings between all objects and policies. Therefore, we need to specify the Post model policy to the PostPolice class:

   PostPolicy::class,   ];   /**    * Register any application authentication / authorization services.    *     * @param \Illuminate\Contracts\Auth\Access\Gate $gate    * @return void    */    public function boot(GateContract $gate)    {      $this->registerPolicies($gate);     }}
Write policy

Once a policy is generated and registered, we can add verification methods for authorization of all capabilities. For example, let's define an update method in the PostPolicy class to verify whether the given user has the ability to update Post:

  id === $post->user_id;   }}

You can continue to add other authorization verification methods in the policy. For example, you can continue to define show, destroy, or addComment methods to verify the various actions of Post.

Note: All policy classes are parsed by service containers. This means that you can use the type prompt to inject the dependencies required by the policy class constructor.

Intercept all checks

Sometimes, you may need to issue a pass to a specified user with all the capabilities. at this time, you can define the before method in the strategy class. This method runs before all other methods in the policy are executed:

public function before($user, $ability){  if ($user->isSuperAdmin()) {    return true;  }}

If the before method returns a non-null value, the result is used as the basis for determining the authorization verification result.

Check policy

The policy method is called as Closure in the same way as the authorization callback method. You can use the Gate mask, User model, @ can Blade command or policy helper for authorization check.

Pass the Gate mask

Gate checks the type of parameters passed to the method to determine which policy should be used. Therefore, if we pass the Post instance to the denies method, Gate will automatically use the corresponding PostPolicy for authorization verification:

     

Use the user model

The can and cannot methods in the User model automatically match the corresponding policy when the given parameters are available. These methods provide a convenient way to verify whether any user instance has the given capabilities:

if ($user->can('update', $post)) {  //}if ($user->cannot('update', $post)) {  //}

Use the Blade Template

As we expected, the @ can Blade command will automatically match the corresponding policy when the given parameter is available:

@can('update', $post)  
   @endcan

By policy Helper

The global help method policy can parse the corresponding Policy class through the given class. For example, we can pass a Post instance to the policy help method, which will return the corresponding PostPolicy class:

if (policy($post)->update($user, $post)) {  //}
Controller authorization

By default, AuthorizesRequests trait is introduced in laravel based Ap \ Http \ Controllers \ Controller classes ). This feature provides the authorize method to quickly verify whether the given action has the ability to execute. if not, an HttpException is thrown.

The authorize method shares the visa methods of other authorization methods, such as Gate: allows and $ user-> can (). Then, let's use the authorize method to quickly identify whether a request has the ability to update the Post:

   authorize('update', $post);     // Update Post...   }}

If this action is authorized, the controller continues to execute the following logic. Otherwise, an HttpException error is automatically thrown, which generates an Http response of 403 Not Authorized. As you can see, the authorize method is a very convenient method. it is convenient to use only one statement to perform authorization verification or throw an exception.

AuthorizeRequests trait also provides the authorizeForUser method to authenticate non-current users and given capabilities:

$this->authorizeForUser($user, 'update', $post);

Automatic policy determination method

Generally, the methods in the strategy class correspond to the methods in the controller. For example, in the above update method, the controller method and policy method use the same name: update.

For this reason, laravel allows you to simply pass an instance parameter to the authorize method. During capability authentication, laravel automatically determines the call of the policy method based on the name of the current method. In the above example, because the authorize method is called in the update method in the controller, the update in PostPolicy will be called:

/** * Update the given post. *  * @param int $id * @return Response */ public function update($id) {   $post = Post::findOrFail($id);   $this->authorize($post);   // Update Post... }

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.