API Authentication in Laravel

Published on by

API Authentication in Laravel image

When it comes to Authentication in Laravel, there are a lot of options. But what should we use when it comes to authenticating your API?

Traditionally we would lean on something like JSON Web Tokens for our API authentication, similar to session-based authentication for the web. You swap your credentials for something that will provide you with prolonged access.

Then we started using Laravel Passport, a fantastic OAuth implementation that you can use to provide OAuth access to your Laravel applications, whether server-to-server authentication, mobile authentication, or other types of authentication. For a long time, we stuck with using Laravel Passport and the Password Grant type, which allowed us to send over our credentials along with the OAuth application details, and we would get back an access and refresh token - allowing us access and a way to refresh that access when it expired. However, this is no longer recommended as an authentication mechanism as we used to use it.

Where does this leave us? Is Sanctum the only option recommended? Well, yes and no. Sanctum was designed as a lightweight alternative to Passport, but in reality, it has achieved a lot more than that. Whether you are building a web application, client implementation, or anything in-between - sanctum has quickly become the gold standard authentication mechanism within the Laravel ecosystem.

What does that mean for APIs, though? Do we need to pass over a name for the token each time we want to authenticate? Well, you can do it - it won't hurt anyone. However, how do I authenticate my APIs in Laravel?

Let's walk through my approach and see why this works/makes sense. It starts with the users' credentials - like any suitable authentication mechanism. We post these to our log-in or register endpoints - and Laravel does some magic for us (depending on the package we use).

Suppose we are using Laravel Breeze or Jetstream. In that case, the authentication provided will create a session-based cookie for us - which our implementation can then use for every subsequent request to prove its authenticated state. Now, this confused me a little. I was wondering where my token should be and what I have on my side to prove I am authenticated other than a cookie. I was so used to dealing with this token, or that token, that I was able to use it to prove my identity. Cookies were for the web, right? I wasn't seeing my API as a web API, which shows we can all be slightly naive sometimes.

Suppose I were to build a CLI application, mobile application, or some integration that needs to work with my local system as something installable. In that case, we can use Sanctum to pass over a name to create the token that needs storing - which feels natural. Our API, however, may have an integration through a Single Page Application - or even another application also built in Laravel. That part doesn't matter, as it isn't something we are installing.

The best way to approach authentication is to follow what I would call a simple guide:

You are building something that is accessed, not installed. In this situation, you should use Laravel Sanctum with cookie-based authentication. A cookie can be configured to be as long or short-lived as your access needs to be, and when the access stops, the authentication can do too.

You are building something that is installed on a user's device. This is where we need to make a couple of choices. Is the access something that needs to be controlled on an identity basis? In other words - does the application have access to everything, and there isn't an authorization layer? Laravel Passport using client credentials is a good call if this is the case. Laravel Passport has a grant type called Client Credentials: where you authenticate a client not a user - so whoever has access to the client can control the system. You can take this a little further with PKCE, where you cannot guarantee the confidentiality of the client's secret.

If you need to authenticate a user, not a client - then lean on Laravel Sanctum and pass over a unique name for the installed application - so that you can store the provided token and use it repeatedly.

The biggest problem with using Laravel Sanctum is that you must fetch a cross-site request cookie to make requests to your Laravel API. When building a SPA, this isn't a problem and is a better approach than storing a JSON web token in local storage.

Steve McDougall photo

Technical writer at Laravel News, Developer Advocate at Treblle. API specialist, veteran PHP/Laravel engineer. YouTube livestreamer.

Cube

Laravel Newsletter

Join 40k+ other developers and never miss out on new tips, tutorials, and more.

Laravel Forge logo

Laravel Forge

Easily create and manage your servers and deploy your Laravel applications in seconds.

Laravel Forge
Tinkerwell logo

Tinkerwell

The must-have code runner for Laravel developers. Tinker with AI, autocompletion and instant feedback on local and production environments.

Tinkerwell
No Compromises logo

No Compromises

Joel and Aaron, the two seasoned devs from the No Compromises podcast, are now available to hire for your Laravel project. ⬧ Flat rate of $7500/mo. ⬧ No lengthy sales process. ⬧ No contracts. ⬧ 100% money back guarantee.

No Compromises
Kirschbaum logo

Kirschbaum

Providing innovation and stability to ensure your web application succeeds.

Kirschbaum
Shift logo

Shift

Running an old Laravel version? Instant, automated Laravel upgrades and code modernization to keep your applications fresh.

Shift
Bacancy logo

Bacancy

Supercharge your project with a seasoned Laravel developer with 4-6 years of experience for just $2500/month. Get 160 hours of dedicated expertise & a risk-free 15-day trial. Schedule a call now!

Bacancy
Lucky Media logo

Lucky Media

Get Lucky Now - the ideal choice for Laravel Development, with over a decade of experience!

Lucky Media
Lunar: Laravel E-Commerce logo

Lunar: Laravel E-Commerce

E-Commerce for Laravel. An open-source package that brings the power of modern headless e-commerce functionality to Laravel.

Lunar: Laravel E-Commerce
LaraJobs logo

LaraJobs

The official Laravel job board

LaraJobs
SaaSykit: Laravel SaaS Starter Kit logo

SaaSykit: Laravel SaaS Starter Kit

SaaSykit is a Multi-tenant Laravel SaaS Starter Kit that comes with all features required to run a modern SaaS. Payments, Beautiful Checkout, Admin Panel, User dashboard, Auth, Ready Components, Stats, Blog, Docs and more.

SaaSykit: Laravel SaaS Starter Kit
Rector logo

Rector

Your partner for seamless Laravel upgrades, cutting costs, and accelerating innovation for successful companies

Rector
MongoDB logo

MongoDB

Enhance your PHP applications with the powerful integration of MongoDB and Laravel, empowering developers to build applications with ease and efficiency. Support transactional, search, analytics and mobile use cases while using the familiar Eloquent APIs. Discover how MongoDB's flexible, modern database can transform your Laravel applications.

MongoDB

The latest

View all →
The Inertia.js v2 Beta is Here image

The Inertia.js v2 Beta is Here

Read article
Mastering Laravel, No Compromises, and SourceDive with Joel Clermont image

Mastering Laravel, No Compromises, and SourceDive with Joel Clermont

Read article
Now you can install PHP and the Laravel installer with a single command image

Now you can install PHP and the Laravel installer with a single command

Read article
WireSpy is a Sleek New Debug Bar for Laravel Livewire image

WireSpy is a Sleek New Debug Bar for Laravel Livewire

Read article
The Laracon AU schedule is now live image

The Laracon AU schedule is now live

Read article
Supercharge PhpStorm with Laravel Idea image

Supercharge PhpStorm with Laravel Idea

Read article