laravel - middleware 'auth:sanctum' always fails

84 views Asked by At

I used laravel 10 to make a login API and it works and returns a token.

This a sample of returned tokens: 17|TlLRhxxWLRwP9fElWFNNg63XI99WFMEi3fSiZ61w1909a9d1

and this is the controller action:

public function loginApi(Request $request)
    {
        $data = $request->validate([
            'username' => 'required',
            'password' => 'required'
        ]);

        if (auth()->attempt($data)) {
            $user = User::where('username', $data['username'])->first();
            $token = $user->createToken('token')->plainTextToken;
            return $token;
        }
        return response('Invalid values!', 400);
    }

After that I made a new API route to create posts; this is the route in api.php:

Route::post('/create-post', [PostController::class, 'insertApi'])->middleware(['auth:sanctum']);

but when I try to send the request, it always kicks me back to home page which means authorization fails.

I used "postman" and "insomnia" to send the requests and in authorization tab clicked the Bearer Token and pasted the token for authorization, but as I said, it kicks me back to home page...

request header:

enter image description here

response header:

enter image description here

Could someone please tell me what is the problem?

0

There are 0 answers