Home > database >  Do I get a 422 HTTP code even though I am logged in?
Do I get a 422 HTTP code even though I am logged in?

Time:12-17

Do I get a 422 HTTP code even though I am logged in? From my blade I send an XHR post request. In the route I use the auth middleware. This works. This means you have to be logged in to send the post.

web.php

Route::post('/posts', [PostController::class, 'store'])->middleware(['web', 'auth'])->name('posts.store');

Now I created my own request class to validate the sent data.

PostStoreRequest authorise method

public function authorize()
{
    return false;
}

Since I use my own custom request class I get this error message even though I am logged in:

This action is unauthorized.", exception: "Symfony\\Component\\\HttpKernel\\Exception\\AccessDeniedHttpException

I wonder why this is?

CodePudding user response:

You have to check in the authorize() method if the user is authorised for this action. If you have a role system right you can implement this here. For example, only users with the Writer role are allowed to create a post. If you don't have that and you just allow everyone who is logged in, then change the return to true or return auth()->check().

Example without role system:

public function authorize()
{
    return true;
    // or
    return auth()->check();
}

With role System:

public function authorize()
{
    return auth()->user()?->isWriter();
}

Important Note: Thank to @matiaslauriti && @Tpojka for the right advice / good review.

  • Related