简体   繁体   中英

Best practice to place sanctum $user->tokenCan() check

I am following a tutorial on building an API in Laravel. I have reached the stage of Authentication/Authorisation and have a question about best practices.

The tutorial uses "Requests" for validation on the controller's 'store' method and in the 'authorize' method of this request, the following code is placed.

    public function authorize()
    {    
        $user = $this->user();
        return $user != null && $user->tokenCan('create');
    }

That works great and I completely understand it. However, I want to authorise non writing methods in the controller as well (index, show, destroy etc). Now, I can easily place the tokenCan check in the controller methods, and that works great too. But it does seem the wrong way of doing it. Some authorisation is happening in the controller, some in the Requests. I would have thought the right way is to keep the token checks in the same place.

So my question is, what is the correct location to place the token check in this scenario? Would placing all checks into the controller and simply returning true in the Request have any adverse effects? Should I be doing the token check in the routes file instead?

Using a middleware solves all of your issues. DRY principle

Like others have pointed out, heres the doc https://laravel.com/docs/9.x/sanctum#protecting-routes

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM