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>" \