I’m building a Laravel application with Vue inside the application–not Vue as a seperate SPA. I will not be making any external API calls to my Laravel app–only internal calls.
With a fresh Laravel installation, I cannot use api.php routes without token authentication setup. Try requesting “/api/user” and despite being authenticated via the web based session authentication Laravel provides you cannot access this endpoint.
It is true that I could place my API routes within my web.php routes file and everything would work. But, I want to keep my API routes separate like I do with my controllers. Additionally, when I decide to implement Airlock or Passport my routes will be where they need to be.
Until I’m ready to expose my API endpoints outside my Laravel app, I will use session based authentication for my API routes. It turns out this is easy to setup. Let me show you.
We can do this in 4 steps
Set “SESSION_DRIVER” to equal “cookie” in your “.env” file.
Change your API guard in “config/auth.php” to use session.
Add the following middleware to “api” within “app/Http/Kernal.php”:
\App\Http\Middleware\EncryptCookies::class, \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class, \Illuminate\Session\Middleware\StartSession::class, \App\Http\Middleware\VerifyCsrfToken::class,
This middleware instructs your API routes to treat cookies the same way your web routes do.
Please note, the most important middleware here is “…VerifyCsrfToken::class”. This ensures that a CSRF token exists in your API calls and prevents cross site request forgery. When you start using your API routes with Vue and Axios those requests will include your CSRF token automatically. This is because on line 24 of “resources/js/bootstrap.js” that CSRF token is set within Axios’s default headers.
Within “routes/api.php” change “middleware(‘auth:api’)” on your “/user” endpoint to “middleware(‘auth’)”. Now, you can hit that endpoint and resource the currently authenticated user–that’s you!
Also notice how you would secure a route group. It was not immediately apparent to me that I could not use the “middleware()” attribute on a route group.
If you have questions or found errors in my explanation, please post a comment so that I may improve this article.