lundi 17 octobre 2022

Laravel 9 - How to validate user with sanctum in Request

I have a route with the sanctum middleware, the idea of ​​this route is that only those users with a token can access it.

If I make a call with a correct token, the method works, if I try to make the query with an INVALID token, it returns an error that I can't control.

What I try by code is that if the token is not valid, it returns a 401 (unauthorized)

Route

Route::middleware('auth:sanctum')->post('cars', [CarsController::class, 'videoStore'])
    ->name('api.cars.store');

Request

 /** 
 * @param CarStoreRequest $request
 * @return Application|ResponseFactory|\Illuminate\Http\Response
 */
 public function carStore (CarStoreRequest $request)
 {

     $user = Auth::user();

     if ($user === null) {
         return response('Unauthorized', Response::HTTP_UNAUTHORIZED);
    }
 }

API action

<?php

namespace App\Http\Requests\V1;

use Illuminate\Foundation\Http\FormRequest;

class CarStoreRequest extends FormRequest
{

    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        return true;
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {

        return [
            'image' => 'required|mimes:jpeg,jpg|max:30000',
        ];
    }
}

This is the error received with 401 http status code.

{
    "message": "",
    "exception": "Symfony\\Component\\HttpKernel\\Exception\\HttpException",
    "file": "C:\\xampp\\htdocs\\test-api\\vendor\\laravel\\framework\\src\\Illuminate\\Foundation\\Application.php",
    "line": 1151,
    "trace": [
        {
            "file": "C:\\xampp\\htdocs\\test-api\\vendor\\laravel\\framework\\src\\Illuminate\\Foundation\\helpers.php",
            "line": 45,
            "function": "abort",
            "class": "Illuminate\\Foundation\\Application",
            "type": "->"
        },
        {
            "file": "C:\\xampp\\htdocs\\test-api\\app\\Exceptions\\Handler.php",
            "line": 56,
            "function": "abort"
        },


via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire