Categories
Laravel Tutorial

How to secure internal Laravel API routes without Airlock or Passport

Why?

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

Step 1

Set “SESSION_DRIVER” to equal “cookie” in your “.env” file.

.env file

Step 2

Change your API guard in “config/auth.php” to use session.

config/auth.php

Step 3

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,
app/Http/Kernal.php

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.

Step 4

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!

routes/api.php

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.

Questions? Improvements?

If you have questions or found errors in my explanation, please post a comment so that I may improve this article.

Leave a Reply

Your email address will not be published. Required fields are marked *