Laravel 7 — Create an API and Authenticate It with Sanctum

Julian Orozco
4 min readApr 23, 2020

--

This guide is for developers familiar with Laravel and wants to learn more about Laravel 7 and Sanctum authentication.

Prerequisites

In this guide, you will develop a functional API with Laravel 7.2 and its authentication system Sanctum that any client application can use.

Creating the Project

Create your new project by running either of the following commands on your terminal:

laravel new [name] or composer create-project — prefer-dist laravel/laravel [name]

Installing and Configuring Sanctum

After you create your project, install Sanctum in your project, and update some files to implement Sanctum.

Step #1 Install Laravel Sanctum

Run the following command to Install Laravel Sanctum:
composer require laravel/sanctum

Step #2 Publish the Sanctum Configuration and Migration Files

Publish the Sanctum configuration and migration files using the next Artisan command. The sanctum configuration file will be placed in your config directory automatically:

php artisan vendor:publish — provider=”Laravel\Sanctum\SanctumServiceProvider”

Step #3 Run the Database Migrations

Run the database migrations to create the database table for the API tokens with the following command:

php artisan migrate

Step #4 Add Sanctum’s Middleware

Add Sanctum’s middleware to your API middleware group with the next command

app/Http/Kernel.php

// this lineuse Laravel\Sanctum\Http\Middleware\EnsureFrontendRequestsAreStateful;protected $middlewareGroups = [‘api’ => [  // this line  EnsureFrontendRequestsAreStateful::class,  ‘throttle:60,1’,  \Illuminate\Routing\Middleware\SubstituteBindings::class,  ],];],

Step #5 Use Tokens for Users

To use tokens for users, add the HasApiTokens trait inside the User model.

app/User.php

use Laravel\Sanctum\HasApiTokens;class User extends Authenticatable{  use HasApiTokens, Notifiable;}

Creating the Database Seeder

The seeder is executed to populate the database with information to test the API.

Step #1 Create the Seeder

Create the seeder for the User model. You use it in a future step to test your Login endpoint:

php artisan make:seeder UsersTableSeeder

Step #2 Insert a New User

Insert a new user with their information.

DB::table(‘users’)->insert([  ‘name’ => ‘[YOUR NAME]’,  ‘email’ => ‘[SOME EMAIL]’,  ‘password’ => Hash::make(‘[SOME_PASSWORD]’)]);

Step #3 Populate the Users’ Table

Populate the users’ table with the new user by running the following:

php artisan db:seed — class=UsersTableSeeder

Note: To verify that the user has been created correctly, you can install MySQL Workbench and do a SELECT to the user’s table.

Creating the Authentication Controller

After populating the database, create the authentication controller where your login function will live by following these steps:

Step #1 Create the Authentication controller by running:

php artisan make:controller AuthController

Step #2 Open the AuthController.php file and add the following code for the login function:

public function login(Request $request){  try {    $request->validate([      ‘email’ => ‘email|required’,      ‘password’ => ‘required’    ]);    $credentials = request([‘email’, ‘password’]);    if (!Auth::attempt($credentials)) {      return response()->json([        ‘status_code’ => 500,        ‘message’ => ‘Unauthorized’      ]);    }    $user = User::where(‘email’, $request->email)->first();    if ( ! Hash::check($request->password, $user->password, [])) {       throw new \Exception(‘Error in Login’);    }    $tokenResult = $user->createToken(‘authToken’)->plainTextToken;    return response()->json([      ‘status_code’ => 200,      ‘access_token’ => $tokenResult,      ‘token_type’ => ‘Bearer’,    ]);  } catch (Exception $error) {    return response()->json([      ‘status_code’ => 500,      ‘message’ => ‘Error in Login’,      ‘error’ => $error,    ]);  }}

Note: Remember, this is a simple login function for learning purposes. You can add more validations or anything you need to do while the user is logging in.

Routing the API

As this is an API, you define the routes in the api.php file

Add the routes that require authentication inside the middleware group. As the login route doesn’t use the authentication middleware, it goes outside the middle group.

routes/api.php

Route::post(‘/login’, ‘Auth\AuthController@login’);Route::middleware([‘auth:sanctum’])->group(function () {  Route::get(‘/users’, ‘UserController@index’);});

By defining the routes, the GET request requires a new Authorization header to fetch the users. The same is applicable to POST, PUT, and DELETE requests, which return an Unauthorized status code if the token isn’t sent in the headers. The following image is an example of how this configuration looks in Postman.

Authorization = Bearer [API token]
Figure 1. Example of the Postman Configuration

Creating Requests

Create a POST request from the Postman app into the API.

  1. Run this command in your terminal window:

php artisan serve

This command exposes the API in http://127.0.0.1:8000 to be hit by a request.

2. In Postman, hit the Login endpoint.

The response contains the token and the type. The following image depicts how it looks:

Figure 2. Example of the Postman Request

Send a GET request to retrieve all users.
Remember that as this route is using the Sanctum middleware, you must send the token received in the login request and append it in the header as an Authorization header.

The URL is similar to the following:

http://127.0.0.1:8000/api/users
  1. Add the Authorization header.
  2. Click the Send button.

Note: If you try removing the Authorization header and sending the request again, then you should receive an error as a response.

And there you have it, an authenticated API with Sanctum in simple steps.

--

--