I have set up an API token for my users which they can optionally provide when accessing API routes for additional data to be returned.
This is my auth.php configuration:
'defaults' => [
'guard' => 'web',
],
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'eloquent',
],
'api' => [
'driver' => 'token',
'provider' => 'eloquent',
],
],
I have various (shared) places in my code which use checks like $request->user()
without providing the guard. The problem is that this always uses the default guard.
However if I set one of the API routes as to use middleware auth:api
then it uses the api guard by default as I'd expect. I can't really set that up though because as I mentioned, authentication is optional and using the auth middleware makes it mandatory.
I'm wondering if there's a way to set all API routes such that their default guard is the API guard.
By default, web routes are configured to use the web guard and API routes are configured to use the api guard, and unless otherwise specified, Laravel will use the web guard by default. This is specified in your config/auth. php file and you are free to change this as needed.
Route groups allow you to share route attributes, such as middleware or namespaces, across a large number of routes without needing to define those attributes on each individual route. Shared attributes are specified in an array format as the first parameter to the Route::group method.
At its core, Laravel's authentication facilities are made up of "guards" and "providers". Guards define how users are authenticated for each request. For example, Laravel ships with a session guard which maintains state using session storage and cookies.
For me the easiest was to add to the Api\Controller (The one that extends all your classes), the following line:
public function __construct()
{
// We set the guard api as default driver
auth()->setDefaultDriver('api');
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With