phplaravellaravel-livewirelaravel-sanctum

How do I authorise users in Laravel Livewire?


New to Livewire. I saw in the Livewire docs that you can use $this->authorize() alongside Policies to validate certain actions.

My question is, what user am I authorizing exactly?

I'm using Laravel Sanctum for authentication, and normally I'd have the token passed into an Authorization header, which is read in a Request. But how would that be done in this case? At what point is the authenticated user defined?

Or am I doing it completely wrong?

Currently, I have a LoginForm component with the following function:

public function submit(UserService $userService)
{
    $response = $userService->auth(
        $this->only(['email', 'password'])
    );

    if (! $response['success']) {
        session()->flash('error', $response['message']);

        return $this->redirectRoute('login');
    }

    // Store access token
    session('token', $response['token']);

    return $this->redirectRoute('home')  ;
}

I then use the session('token') within the code to authenticate the user.


Solution

  • The documentation does say it's a method of the Livewire component but to understand how it works take a look at the Laravel docs: Authorizing Actions Using Policies > Via Controller Helpers.

    Laravel provides a helpful authorize method to any of your controllers which extend the App\Http\Controllers\Controller base class.

    Like the can method, this method accepts the name of the action you wish to authorize and the relevant model. If the action is not authorized, the authorize method will throw an Illuminate\Auth\Access\AuthorizationException exception

    Looking at the source code we can see authorise is a wrapper for the Gate::authorise function:

    public function authorize($ability, $arguments = [])
    {
        [$ability, $arguments] = $this->parseAbilityAndArguments($ability, $arguments);
    
        return app(Gate::class)->authorize($ability, $arguments);
    }
    

    In the documentation for Authorizing Actions it says:

    Note that you are not required to pass the currently authenticated user to these methods. Laravel will automatically take care of passing the user into the gate closure.

    So in answer to the question "what user am I authorizing exactly?" it is the currently authenticated user.

    If there is no authenticated user the authorize function throws an AuthorizationException exception just as if they are not permitted to perform that action.

    If you want to check a user other than the currently authenticated user, use the forUser method on the Gate facade::

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