Laravel / Laravel API Development

Implementing JWT and Sanctum Authentication

This tutorial will show you how to secure your Laravel API using JWT and Sanctum authentication. You'll learn how to handle authentication and protect your routes and resources.

Tutorial 2 of 5 5 resources in this section

Section overview

5 resources

Covers building RESTful APIs using Laravel for modern web applications.

1. Introduction

Brief explanation of the tutorial's goal

This tutorial aims to guide you through the process of implementing JWT (JSON Web Tokens) and Sanctum Authentication in a Laravel API. This will help you secure your application by ensuring only authenticated users can access specific routes.

What the user will learn

By the end of this tutorial, you will be able to:
- Understand JWT and Sanctum authentication
- Implement JWT authentication
- Implement Sanctum authentication
- Secure routes using these authentication methods

Prerequisites

Before proceeding, you should have:
- Basic knowledge of Laravel and its structure
- PHP environment set up with Laravel installed
- A text editor, such as Visual Studio Code
- Basic knowledge of API development

2. Step-by-Step Guide

JWT Authentication

JWT authentication involves generating a token when the user logs in and then sending this token with each request to authenticate the user.

  1. Install JWT Package: To use JWT in Laravel, we need to install the tymon/jwt-auth package. Run composer require tymon/jwt-auth in your terminal.

  2. Generate JWT Secret: Next, generate a JWT secret using php artisan jwt:secret. This will update your .env file with a new line: JWT_SECRET=secret.

  3. Implement JWT: In your AuthController, use the JWT package to implement authentication. Below is a simplified version:

public function login(Request $request) {
    $credentials = $request->only('email', 'password');

    if (! $token = auth()->attempt($credentials)) {
        return response()->json(['error' => 'Invalid credentials'], 401);
    }

    return response()->json(['token' => $token]);
}

Here, we attempt to validate the user's credentials. If valid, a JWT token is generated and returned.

Sanctum Authentication

Sanctum provides a featherweight authentication system for SPAs (single page applications), mobile applications, and simple, token-based APIs.

  1. Install Sanctum Package: Install the laravel/sanctum package using composer by running composer require laravel/sanctum.

  2. Publish Sanctum Configuration: Next, publish the Sanctum configuration and migration files using php artisan vendor:publish --provider="Laravel\Sanctum\SanctumServiceProvider".

  3. Run Migrations: Run php artisan migrate to create the necessary database tables.

  4. Configure API Middleware: In your api middleware group, ensure you have the EnsureFrontendRequestsAreStateful::class and Authenticate::class.

  5. Use Sanctum's Capabilities: Sanctum offers many methods for authentication, such as check, user, guard and more. Here's a simplified usage example:

public function user(Request $request)
{
    return $request->user();
}

This method will return the authenticated user's instance.

3. Code Examples

JWT Authentication

The following is a more in-depth example of a login method using JWT:

public function login(Request $request) {
    $credentials = $request->only('email', 'password');

    if (!$token = JWTAuth::attempt($credentials)) {
        return response()->json(['error' => 'Invalid credentials'], 401);
    }

    return response()->json(['token' => $token]);
}

This method receives a request, attempts to authenticate the user, and if successful, returns a JWT.

Sanctum Authentication

Consider this example of a route that requires authentication:

Route::middleware('auth:sanctum')->get('/user', function (Request $request) {
    return $request->user();
});

This route will return the authenticated user's instance, or a 401 status code if the user is not authenticated.

4. Summary

In this tutorial, we've covered JWT and Sanctum authentication in Laravel. We've learned how to install necessary packages, generate tokens, and protect routes. We've also provided examples of how to authenticate users and return authenticated user's instances.

5. Practice Exercises

  1. Exercise 1: Create a registration route that returns a JWT token upon successful registration.

  2. Exercise 2: Create a route that requires Sanctum authentication and returns a list of all registered users.

  3. Exercise 3: Create a logout route that invalidates the user's JWT token.

Remember, the key to mastering these concepts is practice. Try implementing these methods in your projects, and experiment with different methods offered by both packages to familiarize yourself with their capabilities.

Need Help Implementing This?

We build custom systems, plugins, and scalable infrastructure.

Discuss Your Project

Related topics

Keep learning with adjacent tracks.

View category

HTML

Learn the fundamental building blocks of the web using HTML.

Explore

CSS

Master CSS to style and format web pages effectively.

Explore

JavaScript

Learn JavaScript to add interactivity and dynamic behavior to web pages.

Explore

Python

Explore Python for web development, data analysis, and automation.

Explore

SQL

Learn SQL to manage and query relational databases.

Explore

PHP

Master PHP to build dynamic and secure web applications.

Explore

Popular tools

Helpful utilities for quick tasks.

Browse tools

EXIF Data Viewer/Remover

View and remove metadata from image files.

Use tool

Text Diff Checker

Compare two pieces of text to find differences.

Use tool

Watermark Generator

Add watermarks to images easily.

Use tool

URL Encoder/Decoder

Encode or decode URLs easily for web applications.

Use tool

WHOIS Lookup Tool

Get domain and IP details with WHOIS lookup.

Use tool

Latest articles

Fresh insights from the CodiWiki team.

Visit blog

AI in Drug Discovery: Accelerating Medical Breakthroughs

In the rapidly evolving landscape of healthcare and pharmaceuticals, Artificial Intelligence (AI) in drug dis…

Read article

AI in Retail: Personalized Shopping and Inventory Management

In the rapidly evolving retail landscape, the integration of Artificial Intelligence (AI) is revolutionizing …

Read article

AI in Public Safety: Predictive Policing and Crime Prevention

In the realm of public safety, the integration of Artificial Intelligence (AI) stands as a beacon of innovati…

Read article

AI in Mental Health: Assisting with Therapy and Diagnostics

In the realm of mental health, the integration of Artificial Intelligence (AI) stands as a beacon of hope and…

Read article

AI in Legal Compliance: Ensuring Regulatory Adherence

In an era where technology continually reshapes the boundaries of industries, Artificial Intelligence (AI) in…

Read article

Need help implementing this?

Get senior engineering support to ship it cleanly and on time.

Get Implementation Help