Laravel Sanctum login

Viewed 7559

I need to create a login with Laravel 8 and Sanctum. I have a Laravel application without Vue.js / React or Angular and I need to create tokens for api.

When I create a token, authorization on the API works great but doesn't work for the web.

I just need to log in and then create a token that can be used for API and of course let the data be stored in the session or cookies so that he can use the web.

Or can you recommend something to me about how it could be solved?

1 Answers

Laravel Sanctum is a new powerful package that makes authentication easier for different scenarios:

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.

The following Controller allows an user to login and create a token via Laravel sanctum:

<?php

namespace App\Http\Controllers;

use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;

class AuthController extends Controller
{
   public function store(Request $request)
   {
      $request->validate([
         'email' => 'required|email',
         'password' => 'required',
         'device_name' => 'required',
      ]);

      $user = User::where('email', $request->email)->first();

      if (!$user || !Hash::check($request->password, $user->password)) {
         return response('Login invalid', 503);
      }

      return $user->createToken($request->device_name)->plainTextToken;
   }
}

We can register a route that will be managed by the Controller above:

// routes/web.php or routes/api.php
Route::post('/login', [AuthController::class, 'store']);
Route::group(['middleware' => 'auth:sanctum'], function () {
// Route that needs the user to be logged in
/*
Route
   ::get('/dashboard', [DashboardController::class, 'index'])
   ->name('dashboard');
      */
});

Therefore, the following POST request with valid credentials will return a token:

curl -d "email=admin&password=123&device_name=test" -X POST https://localhost:8000/login

Which we can then use to make the next authenticated API calls:

curl -i https://localhost:8000/dashboard \
  -H "Authorization: Bearer <TOKEN_FROM_PREVIUOS_COMMAND>" \
Related