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

Educator and Content creator, freelance consultant, API evangelist

Cube

Laravel Newsletter

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

Curotec logo

Curotec

Hire the top Latin American Laravel talent. Flexible engagements, budget optimized, and quality engineering.

Curotec
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
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
Cut PHP Code Review Time & Bugs into Half with CodeRabbit logo

Cut PHP Code Review Time & Bugs into Half with CodeRabbit

CodeRabbit is an AI-powered code review tool that specializes in PHP and Laravel, running PHPStan and offering automated PR analysis, security checks, and custom review features while remaining free for open-source projects.

Cut PHP Code Review Time & Bugs into Half with CodeRabbit
Join the Mastering Laravel community logo

Join the Mastering Laravel community

Connect with experienced developers in a friendly, noise-free environment. Get insights, share ideas, and find support for your coding challenges. Join us today and elevate your Laravel skills!

Join the Mastering Laravel community
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
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
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 →
Solo Dumps for Laravel image

Solo Dumps for Laravel

Read article
Download Files Easily with Laravel's HTTP sink Method image

Download Files Easily with Laravel's HTTP sink Method

Read article
Aureus ERP image

Aureus ERP

Read article
Precise Collection Filtering with Laravel's whereNotInStrict image

Precise Collection Filtering with Laravel's whereNotInStrict

Read article
Configuring Middleware in Laravel image

Configuring Middleware in Laravel

Read article
Come for the Simplicity, Stay for the Extensibility: Identity with FusionAuth image

Come for the Simplicity, Stay for the Extensibility: Identity with FusionAuth

Read article