Laravel Sanctum [In-Depth Tutorial]


Written By - Muhammad Azeem
Advertisement

Introduction

Definition of Laravel Sanctum

Laravel Sanctum is a lightweight authentication system for single-page applications, mobile applications, and traditional, browser-based web applications. It provides an authentication layer for Laravel applications, allowing developers to easily create and manage authentication tokens for their users.

To explain the concept of Laravel Sanctum, let's take an example of a web application that allows users to log in and view their account details, edit their profile, and purchase items. Because the application is a web application, it requires a secure authentication system that will protect the user's data. The application could use a username and password system, but this can be difficult to manage and secure.

Using Laravel Sanctum, the application can instead use authentication tokens to securely authenticate the user. This works by having the user log in to the application once and then being issued a token. This token is then used in subsequent requests to authenticate the user without having to log in again. The token is securely stored on the server, making it difficult for malicious actors to gain access to the user's data.

The benefit of using Laravel Sanctum is that it is a lightweight authentication system that is easy to implement and manage. It is also highly secure, as the authentication tokens are stored securely on the server. This makes it difficult for malicious actors to gain access to the user's data.

Overall, Laravel Sanctum is an excellent choice for web applications that require secure authentication. It is easy to implement and manage, and provides a secure authentication layer for web applications.

 

Benefits of using Laravel Sanctum

Laravel Sanctum is an advanced authentication package for Laravel applications that enables developers to build multi-authentication systems for their websites. It provides an easy-to-use and secure authentication system that can be used to authenticate both users and API clients. With Laravel Sanctum, developers can quickly and easily add authentication to their web applications, as well as quickly create new authentication tokens for both user and API-based authentication.

One of the main benefits of using Laravel Sanctum is that it helps developers build secure and efficient authentication systems. By utilizing built-in security features, such as two-factor authentication and password hashing, developers can ensure that their applications are secure and their users are protected. Additionally, Laravel Sanctum provides developers with an easy-to-use API that allows them to quickly create and manage authentication tokens for both user and API authentication.

Another benefit of using Laravel Sanctum is that it enables developers to quickly create and manage authentication tokens for both user and API authentication. With this system, developers can easily create multiple authentication tokens that can be used to authenticate both users and API clients. Additionally, developers can also specify how long authentication tokens should be valid, allowing them to easily manage and control access to their applications.

Advertisement

Finally, Laravel Sanctum provides developers with an easy-to-use interface for creating and managing authentication tokens. This interface makes it easy for developers to quickly create, manage, and delete authentication tokens for both user and API authentication. Additionally, developers can also quickly search for existing tokens and easily delete them if needed.

For example, if a developer wanted to create a secure authentication system for a website, they could use Laravel Sanctum to create authentication tokens for both user and API authentication. They could then specify the length of the token, as well as the type of authentication that will be used for each authentication token. This would allow the developer to quickly create and manage authentication tokens for both user and API authentication.

Overall, Laravel Sanctum is an advanced authentication package that makes it easy for developers to quickly create and manage authentication tokens for both user and API authentication. By taking advantage of the built-in security features, developers can ensure that their applications are secure and their users are protected. Additionally, Laravel Sanctum provides an easy-to-use and secure API for quickly creating and managing authentication tokens for both user and API authentication.

 

Features of Laravel Sanctum

1. Single Page Applications Support: Laravel Sanctum provides support for Single Page Applications (SPAs). SPAs are web applications that are loaded once and then dynamically update the page with new data as the user interacts with it. Sanctum provides the ability to issue API tokens for SPAs and mobile applications.

2. Token Authentication: Laravel Sanctum provides the ability to issue API tokens for authentication. These tokens are used to authenticate requests to the API and can be easily revoked. This makes it easy to manage authentication for mobile applications and SPAs.

3. Easy Integration: Laravel Sanctum is designed to be easy to use and integrate into existing Laravel projects. This makes it simple to add authentication to a project without having to do a complete rewrite.

 

Example

Let’s take a look at how we can use Laravel Sanctum to authenticate a Single Page Application.

Advertisement

First, we’ll need to install Sanctum. This can be done by running the following command in the terminal:

composer require laravel/sanctum

Next, we’ll need to publish the Sanctum configuration and migrations. This can be done by running the following command in the terminal:

php artisan vendor:publish --provider="Laravel\Sanctum\SanctumServiceProvider"

Next, we’ll need to run the Sanctum migrations. This can be done by running the following command in the terminal:

php artisan migrate

Finally, we’ll need to enable Sanctum in our routes/web.php file:

Route::middleware(['auth:sanctum', 'verified'])->group(function () {
    //
});

Now we can use the Sanctum token authentication in our Single Page Application. We can issue tokens using the Sanctum routes and use them to authenticate requests to the API.

 

How to Use Laravel Sanctum

Setting up Laravel Sanctum

In this article, we will learn how to set up Laravel Sanctum with an example. Before getting started, let us discuss the prerequisites.

Advertisement

Prerequisites

Before we start the installation process, we need to have the following prerequisites:

  • A local development environment set up with a working version of PHP and MySQL.
  • A basic understanding of the Laravel framework.
  • Basic knowledge of Composer and the command line.
  • A working version of Laravel installed on your local development environment.

Installation

Once the prerequisites are ready, we can start the installation process by following these steps:

  1. Install the Laravel Sanctum package using the Composer package manager. The command for this is “composer require laravel/sanctum”.
  2. Publish the config file and migrations with the command “php artisan vendor:publish --provider="Laravel\Sanctum\SanctumServiceProvider"”.
  3. Run the migration command “php artisan migrate”. This will create the database tables required by Laravel Sanctum.
  4. Next, register the Sanctum routes in the routes/web.php file.
  5. Generate the Sanctum encryption keys with the command “php artisan sanctum:install”.
  6. Finally, run the command “php artisan serve” to start the development server.

Example

Let us now create a sample application to demonstrate the usage of Laravel Sanctum.

Create a new route in the routes/web.php file and name it “sanctum”.

Add the following code in the route:

Route::post('sanctum', function(){
    $credentials = request()->only('email', 'password');
    
    $token = auth()->attempt($credentials);
    if ($token) {
        return response(['token' => $token], 200);
    }
    return response([], 403);
});

Now, let us create a controller named “AuthController” with the command “php artisan make:controller AuthController”.

Add the following code in the AuthController:

Advertisement
public function authenticate(Request $request)
{
    $credentials = $request->only('email', 'password');
    if (auth()->attempt($credentials)) {
        $token = auth()->attempt($credentials);
        return response(['token' => $token], 200);
    }
    return response([], 403);
}

Finally, create a view with the name login.blade.php and add the following code to it:

<form action="{{ route('sanctum') }}" method="POST">
    @csrf
    <div>
        <label for="name">Name:</label>
        <input type="text" name="name" id="name" />
    </div>
    <div>
        <label for="password">Password:</label>
        <input type="password" name="password" id="password" />
    </div>
    <div>
        <button type="submit">Submit</button>
    </div>
</form>

 

Creating Authentication Schemes

Authentication is an important aspect of any web application. It is essential to maintain the security of user data and enable users to securely access the application. Laravel Sanctum is a lightweight authentication system for Laravel applications. It provides a clean and simple authentication system for applications without the need for complex session management.

In this article, we will discuss how to create authentication schemes in Laravel Sanctum. We will also provide an example to demonstrate how to implement this authentication scheme.

'schemes' => [
    'token' => [
        'driver' => 'token',
        'provider' => 'users',
    ],
],

In this example, we are defining a token-based authentication scheme with the driver set to “token” and the provider set to “users”. The “users” provider indicates that the authentication will be based on the users table in the database.

We can also configure the Sanctum middleware to add additional security to the authentication process. For example, we can add the “VerifyCsrfToken” middleware to ensure that requests are verified before they are processed:

'middleware' => [
    \Laravel\Sanctum\Http\Middleware\VerifyCsrfToken::class,
],

Once we have configured the authentication scheme and middleware, we can use the Sanctum façade to authenticate users. For example, we can use the “attempt” method to authenticate a user using the token-based authentication scheme that we have created:

$user = Sanctum::attempt(['email' => $email, 'password' => $password]);

If the authentication is successful, the attempt method will return a User object. Otherwise, it will return null.

We can also use the Sanctum façade to generate tokens for a user. For example, we can use the “token” method to generate a token for a given user:

$token = Sanctum::token($user);

The token method will return a token string which can be used to authenticate the user in future requests.

In this article, we have discussed how to create authentication schemes in Laravel Sanctum. We have also provided an example to demonstrate how to implement a token-based authentication scheme. We hope that this article has been helpful in understanding how to use Laravel Sanctum to authenticate users in web applications.

Advertisement

 

Using Sanctum with JavaScript

To use Sanctum with JavaScript, you’ll first need to configure it in your Laravel application. This can be done by adding the Sanctum package to your application’s composer.json file and running the php artisan vendor:publish command. This will create a config/sanctum.php file which you can then configure to enable Sanctum for your JavaScript application.

Once you’ve configured Sanctum for your application, you’ll need to create a route for your JavaScript application to authenticate with Sanctum. This can be done by creating a route in your routes/web.php file with the Sanctum::login method. This route will need to accept a POST request, where the user’s credentials will be passed in the form of a JSON body.

Once the route is created, you’ll need to create a controller to handle the authentication request. In this controller, you’ll need to use the Sanctum::attempt() method to authenticate the user. If the authentication is successful, you’ll need to generate a token and return it to the JavaScript application. This token can then be used to authenticate subsequent requests.

To use the token with your JavaScript application, you’ll need to add an HTTP header to each request containing the token. This header should be called X-CSRF-TOKEN and should contain the token that was returned from the authentication request.

With Sanctum and JavaScript, you can easily secure your web applications and authenticate users. This makes it easy to create robust and secure applications that can be used on any platform. Using Sanctum and JavaScript is a great way to ensure your applications are secure and can be used with confidence.

 

Reasons to Use Laravel Sanctum

Laravel Sanctum provides developers with a secure and reliable way to authenticate users and manage authorization for their applications. It uses token-based authentication to provide user access to specific resources. The tokens are generated and stored in the user’s browser. These tokens are then used to authenticate requests from the user’s browser, so that the user can access the resources they need.

There are several reasons why developers should use Laravel Sanctum for their web applications. First, it is easy to set up and configure, and provides a secure authentication system for both APIs and SPAs. Second, Laravel Sanctum is highly customizable and allows developers to easily set up custom authorization rules for their applications. Third, it provides a streamlined way to manage users and permissions, and is highly scalable. Finally, Laravel Sanctum is compatible with many other frameworks and libraries, making it easy to integrate it into any existing application.

Let’s look at an example of how Laravel Sanctum can be used in a web application. Suppose we have a web application that needs to authenticate users, and also needs to restrict access to certain resources. To do this, we would first need to create an authentication system for the application. We could use Laravel Sanctum to accomplish this.

First, we would need to create a database table to store the users’ credentials. Then, we would need to create a controller to handle authentication requests from the user’s browser. Finally, we would need to define the authorization rules for the application, so that only authenticated users would be able to access the restricted resources.

Once all of the necessary components are set up, Laravel Sanctum would generate a token for each user who successfully authenticates. This token would then be stored in the user’s browser. Every time the user attempts to access a restricted resource, the token would be sent to the server, and the server would then check the token against the database table to make sure the user is authorized to access the resource.

In summary, Laravel Sanctum is an excellent choice for web developers who need a secure authentication system for their applications. It is easy to set up and configure, offers a streamlined way to manage users and permissions, and is compatible with many other frameworks and libraries. With its token-based authentication system, Laravel Sanctum provides developers with a secure and reliable way to authenticate users and manage authorization for their applications.

 

Further Reading

Laravel Sanctum
https://github.com/laravel/sanctum

 

Didn't find what you were looking for? Perform a quick search across GoLinuxCloud

If my articles on GoLinuxCloud has helped you, kindly consider buying me a coffee as a token of appreciation.

Buy GoLinuxCloud a Coffee

For any other feedbacks or questions you can either use the comments section or contact me form.

Thank You for your support!!

Leave a Comment