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

Time:12-01

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?

CodePudding user response:

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

  • Related