Getting Started with API Authentication using Laravel Sanctum
Introduction
In today's world of web development, building secure and reliable APIs is crucial. Laravel, a popular PHP framework, provides various tools to simplify this process. One such tool is Laravel Sanctum, which offers a simple and elegant solution for API authentication. In this blog post, we'll explore the basics of Laravel Sanctum and learn how to implement token-based authentication for your APIs.
What is Laravel Sanctum?
Laravel Sanctum is an official Laravel package designed to provide a lightweight and efficient way to authenticate users for your API endpoints. It's particularly well-suited for single-page applications (SPAs) and mobile applications. Sanctum offers two primary methods of authentication: token-based authentication and session-based authentication.
Setting Up Laravel Sanctum
-
Installation:
To get started, you need a Laravel project up and running. If you don't have one, you can create a new project using Composer:
Next, install Laravel Sanctum using Composer:
-
Configuration:
After installation, you'll need to publish the Sanctum configuration file:
-
Database Migrations:
Run the database migrations to set up the required tables for Sanctum:
-
Configuration and Middleware:
In your
config/sanctum.php
configuration file, you can customize the authentication options, such as the expiration time for tokens. Additionally, make sure you apply theauth:sanctum
middleware to the routes that require authentication.
Creating and Using Tokens
-
Creating Tokens:
To create a token for a user, you can use the
createToken
method on theUser
model: -
Using Tokens:
With the generated token, you can include it in the headers of your API requests using the
Authorization
header with theBearer
scheme:
Protecting API Routes
To protect your API routes, apply the auth:sanctum
middleware to the desired routes or groups of routes. For example:
Revoking Tokens
If a user logs out or you want to revoke a token for any reason, you can revoke all of a user's tokens using the tokens()->delete()
method on the User
model:
Conclusion
Laravel Sanctum provides a streamlined approach to API authentication, making it an excellent choice for modern web and mobile applications. With its easy setup and powerful features, you can ensure the security and integrity of your APIs while providing a seamless experience for your users. Whether you're building a single-page application or a mobile app, Laravel Sanctum has you covered.
In this blog post, we've covered the basics of setting up Laravel Sanctum, creating and using tokens, protecting API routes, and revoking tokens. Armed with this knowledge, you can confidently implement secure authentication for your Laravel applications.