API authentication
We added the auth
middleware to our /api/user/toggle_saved
route to protect it from guest users. We also specified the api
guard for this middleware, that is, auth:api
.
Guards define how users are authenticated and are configured in the following file.
config/auth.php
:
<?php return [ ... 'guards' => [ 'web' => [ 'driver' => 'session', 'provider' => 'users', ], 'api' => [ 'driver' => 'token', 'provider' => 'users', ], ], ... ];
Our web routes use the session driver which maintains authentication state using session cookies. The session driver ships with Laravel and works out-of-the-box. API routes, though, use the token guard by default. We have not yet implemented this driver, hence our AJAX calls are unauthorized.
We could use the session driver for API routes as well, but this is not recommended, as session authentication is not sufficient for AJAX requests. We're instead going to use the passport
guard...