Laravel API Authentication Using Sanctum

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


Introduction

Laravel Sanctum provides a featherweight authentication system for SPAs (single page applications), mobile applications, and simple, token based APIs. Sanctum allows each user of your application to generate multiple API tokens for their account. These tokens may be granted abilities / scopes which specify which actions the tokens are allowed to perform.


Installation

  1. You may install Laravel Sanctum via the Composer package manager:
  2. composer require laravel/sanctum
  3. Next, you should publish the Sanctum configuration and migration files using the vendor:publish Artisan command. The sanctum configuration file will be placed in your application's config directory:
  4. php artisan vendor:publish --provider="Laravel\Sanctum\SanctumServiceProvider"
  5. Sanctum allows you to issue API tokens / personal access tokens that may be used to authenticate API requests to your application. When making requests using API tokens, the token should be included in the Authorization header as a Bearer token.
  6. To begin issuing tokens for users, your User model should use the Laravel\Sanctum\HasApiTokens trait:

    use Laravel\Sanctum\HasApiTokens;
    
    class User extends Authenticatable
    {
      use HasApiTokens;
    }
  7. Finally, you should run your database migrations. Sanctum will create one database table in which to store API tokens:
  8. php artisan migrate
  9. Next, if you plan to utilize Sanctum to authenticate an SPA, you should add Sanctum's middleware to your api middleware group within your application's app/Http/Kernel.php file:
  10. 'api' => [
        \Laravel\Sanctum\Http\Middleware\EnsureFrontendRequestsAreStateful::class,
        'throttle:api',
        \Illuminate\Routing\Middleware\SubstituteBindings::class,
    ],

Sanctum Authentication

We'll create simple user authentication methods via Laravel Sanctum below.

  1. Create Route: Create routes into routes/api.php that point to AuthController:
  2. <?php
    
    use Illuminate\Http\Request;
    use Illuminate\Support\Facades\Route;
    use App\Http\Controllers\AuthController;
    
    /*
    |--------------------------------------------------------------------------
    | API Routes
    |--------------------------------------------------------------------------
    |
    | Here is where you can register API routes for your application. These
    | routes are loaded by the RouteServiceProvider within a group which
    | is assigned the "api" middleware group. Enjoy building your API!
    |
    */
    
    Route::group([
      'prefix' => 'auth'
    ], function () {
      Route::post('login', [AuthController::class, 'login']);
      Route::post('register', [AuthController::class, 'register']);
    
      Route::group([
        'middleware' => 'auth:sanctum'
      ], function () {
        Route::get('logout', [AuthController::class, 'logout']);
        Route::get('user', [AuthController::class, 'user']);
      });
    });
  3. Create Controller: Now, we have to create a controller that handles all API requests. Follow below artisan command to create a new controller:
  4. php artisan make:controller AuthController
  5. Register User: We'll implement a simple method to register a user:
  6. <?php
    
    namespace App\Http\Controllers;
    use Illuminate\Http\Request;
    use Illuminate\Support\Facades\Auth;
    use Carbon\Carbon;
    use App\Models\User;
    use Validator;
    class AuthController extends Controller
    {
      /**
      * Create user
      *
      * @param  [string] name
      * @param  [string] email
      * @param  [string] password
      * @param  [string] password_confirmation
      * @return [string] message
      */
      public function register(Request $request)
      {
          $request->validate([
              'name' => 'required|string',
              'email' => 'required|string|email|unique:users',
              'password' => 'required|string|',
              'c_password'=>'required|same:password',
          ]);
    
          $user = new User([
              'name' => $request->name,
              'email' => $request->email,
              'password' => bcrypt($request->password)
          ]);
    
          if($user->save()){
              return response()->json([
                  'message' => 'Successfully created user!'
              ], 201);
          }else{
              return response()->json(['error'=>'Provide proper details']);
          }
        }
      }

    TEST register user API using postman

    register
  7. Login User: In the same file AuthController.php, create a simple login method that generates API token via sanctum:
  8. /**
    * Login user and create token
    *
    * @param  [string] email
    * @param  [string] password
    * @param  [boolean] remember_me
    * @return [string] access_token
    * @return [string] token_type
    * @return [string] expires_at
    */
    public function login(Request $request)
    {
      $request->validate([
        'email' => 'required|string|email',
        'password' => 'required|string',
        'remember_me' => 'boolean'
      ]);
    
      $credentials = request(['email', 'password']);
      if(!Auth::attempt($credentials))
      {
        return response()->json([
        'message' => 'Unauthorized'
        ], 401);
      }
    
      $user = $request->user();
      $tokenResult = $user->createToken('Personal Access Token');
      $token = $tokenResult->plainTextToken;
    
    
      return response()->json([
        'access_token' => $token,
        'token_type' => 'Bearer',
      ]);
    }

    TEST Login user API using postman

    login
  9. Get User: In the same file AuthController.php, create a simple method to get the user's details:
  10. /**
    * Get the authenticated User
    *
    * @return [json] user object
    */
    public function user(Request $request)
    {
      $user = Auth::user();
      return response()->json($user);
    }

    TEST get user API using postman

    user
  11. Logout User: In the same file AuthController.php, create a simple method to revoke the token from the user:
  12. /**
    * Logout user (Revoke the token)
    *
    * @return [string] message
    */
    public function logout(Request $request)
    {
      $request->user()->tokens()->delete();
    
      return response()->json([
        'message' => 'Successfully logged out'
      ]);
    }

    TEST logout user API using postman

    logout
© 2017- Pixinvent, Hand-crafted & Made with ❤️