i have Laravel Sanctum on this version
- Laravel 11.28
- Sanctum 4.0.3
- PHP 8.3.9
I created an api routes of login just to create a token using createToken() and the process is working just fine with the access token is successfully stored in the personal_access_token in my database and also when hit the api with the Auth Bearer Token of the correct plain text token. My problem is where i hit the api using a wrong Token for examle just a random token i type aaaa as a Bearer Token. The response is HTTP 500 Route [login] not defined. Any idea of how i can only response to just a message like Unauthorized with the json format and not redirecting to a login page, because of my application is an API.
Note that the positive test is all good returning the response as expected, only the wrong auth is not correct. Please help.
Here is some of my code:
routes/api.php
<?php
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Route;
Route::get('/user', function (Request $request) {
return $request->user();
})->middleware('auth:sanctum');
Route::post('/login', function (Request $request) {
$credentials = $request->only('email', 'password');
if (! Auth::attempt($credentials)) {
return response()->json(['message' => 'Invalid credentials'], 401);
}
$user = Auth::user();
$token = $user->createToken('login-token')->plainTextToken;
return response()->json(['token' => $token]);
});
and this i the request i sent using Postman (the authorization is a wrong token so it should be unauthrorized):
curl --location --request GET 'http://127.0.0.1:8000/api/user' \
--header 'Content-Type: application/json' \
--header 'Authorization: ••••••' \
--data-raw '{
"email": "[email protected]"
}'
Thanks a lot.