Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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?

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading