I'm defining my API routes in Laravel 5.4. Most of these routes require authentication, and I would like to be able to do this auth using either:
auth:api
(used by other web apps on different domains) auth
, for AJAX requests in the primary web appIs it possible to do this, or do I have to define all my routes twice, with a different route group prefix or something? eg Do I have to have all session auth API endpoints look like /ajax/api-endpoint
and all token auth API endpoints look like /api/api-endpoint
?
That feels clumsy and arbitrary — I want to access /api/api-endpoint
regardless of the auth method I am using.
Specifying both auth
and auth:api
middlewares as follows appears to make Laravel require BOTH methods of auth before succeeding, instead of just requiring either one:
Route::get('api/user', 'MyUserController@index')->middleware(['auth', 'auth:api']);
define this route Route::get('ajax/user', 'MyUserController@index')
in web.php
and Route::get('api/user', 'MyUserController@index')
in api.php
so the exact same method of controller can be used in both routes, and in your controller method use auth()
to obtain the current user no matter if authentication is performed using auth:api
or only auth auth()
will give you the user that is authenticated by either one method.
assuming you have group in web.php
and api.php
with appropriate middleware applied to group.