I am currently learning Laravel and using Sanctum to perform authentication.
I have a route working /register and /login and I am trying to create /me endpoint that's protected using auth:sanctum which as a test just returns the authenticated user.
In my api.php I have the following:
Route::post('/auth/register', [UserController::class, "register"]);
Route::post('/auth/login', [UserController::class, "login"]);
Route::middleware('auth:sanctum')->get('/me', function(){
return auth()->user();
});
In my UserController class I have the following:
class UserController extends BaseController
{
use AuthorizesRequests, DispatchesJobs, ValidatesRequests;
public function register(Request $request)
{
$user = User::create([
'name' => $request['name'],
'email' => $request['email'],
'password' => bcrypt($request['password'])
]);
return response([
'success' => $user->createToken('API Token')->plainTextToken
]);
}
public function login(Request $request)
{
$attr = $request->validate([
'email' => 'required|string|email|',
'password' => 'required|string|min:6'
]);
if (!Auth::attempt($attr))
{
return response('Credentials not found', 401);
}
return response([
'token' => auth()->user()->createToken('API Token')->plainTextToken
]);
}
public function logout()
{
auth()->user()->tokens()->delete();
return [
'message' => 'Tokens Revoked'
];
}
}
The /login and /register routes work fine, however, when I attempt to use the /logout or /me route which is using auth:sanctum middleware, I get the following error:
Symfony\Component\Routing\Exception\RouteNotFoundException
Route [login] not defined.
Everything I've Google'd seem to show that I've implemented it correctly, so I'm not sure what I'm missing.
I managed to figure out the problem with some help from @LessMore.
I think most of the problem the auth.php being wrong. Under config/auth.php, under the api section change the driver from token to session, so it should be as follows:
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'users',
],
'api' => [
'driver' => 'session',
'provider' => 'users',
'hash' => false,
],
],
The other thing was I was forgetting to add the Authorization header with the bearer token that is returned on the login and to put Accept application/json header.