n Create an API and Authenticate It with Sanctum in Laravel | CodimTh

Please Disable Your Browser Adblock Extension for our site and Refresh This Page!

our ads are user friendly, we do not serve popup ads. We serve responsible ads!

Refresh Page
Skip to main content
On . By CodimTh
Category:

Installing and Configuring Sanctum

 

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

 

Install Laravel Sanctum

Run the following command to Install Laravel Sanctum:


composer require laravel/sanctum

 

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”

 

Run the Database Migrations

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

php artisan migrate

Add Sanctum’s Middleware


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

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

 

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.

 

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

 

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]’)
]);

 

Populate the Users Table

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

php artisan db:seed — class=UsersTableSeeder

 

Creating the Authentication Controller

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

Create the Authentication controller by running:

php artisan make:controller AuthController

 

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,
    ]);
  }
}

 

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]

 

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.

 

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. like this: Authorization = Bearer [API token]
  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.

 

Riadh Rahmi

Senior Web Developer PHP/Drupal & Laravel

I am a senior web developer, I have experience in planning and developing large scale dynamic web solutions especially in Drupal & Laravel.

Web Posts

Search

Page Facebook