Step 2 - Add User Authentication to Laravel App

Continuing from Step 1: https://www.webune.com/forums/laravel-two-commands-to-start-a-new-api-project.html

In this step, you will add backend user authentication as an API for SPA or mobile applications. Once you have completed step 2, you can complete step 3 which is adding authentication to the front end using React.

Open a Bash terminal in your Laravel root app and create two important folders:

$ mkdir app/Http/Controllers/Api; mkdir app/Http/Requests

All in one shot commands

curl -s https://www.webune.com/forums/AuthController.php.html > app/Http/Controllers/Api/AuthController.php
curl -s  https://www.webune.com/forums/LoginRequest.php.html > app/Http/Requests/LoginRequest.php
curl -s  https://www.webune.com/forums/SignupRequest.php.html > app/Http/Requests/SignupRequest.php
code app/Http/Controllers/Api/AuthController.php
code app/Http/Requests/LoginRequest.php
code app/Http/Requests/SignupRequest.php
echo done

IMPORTANT: You must remove the first three top lines to avoid errors of : AuthController.php, LoginRequest.php and SignupRequest.php

YOU SEE THIS ERROR: Namespace declaration statement has to be the very first statement or after any declare call in the script

 

Routes

$ code routes/api.php

Add:

<?php
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\Api\AuthController;
 
Route::middleware('auth:sanctum')->group(function () {
    Route::post('/logout', [AuthController::class, 'logout']);
    Route::get('/user', function (Request $request) {

        return $request->user();
    });

});

Route::post('/signup', [AuthController::class, 'signup']);
Route::post('/login', [AuthController::class, 'login']);

Cors

$ code config/cors.php

Change the following Lines accoring to your requirements. For localhost test development, here is an example:

'paths' => ['*', 'sanctum/csrf-cookie'],

 

'supports_credentials' => true,

 

Postman

POST: http://localhost:8000/api/login

Body > form-data : Email:[email protected], password: test123

Step 3 - Front End

https://www.webune.com/forums/add-authentication-to-react-vite-using-laravel-backend.html