Search code examples
apiauthenticationlaravel-5.4laravel-authorization

Can one Laravel route use either session or token authentication?


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:

  • token authentication i.e. auth:api (used by other web apps on different domains)
  • or using session/cookie auth i.e. auth, for AJAX requests in the primary web app

Is 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']);


Solution

  • 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.