Integrating AngularFrontend with LaravelSanctum Auth 1 (1)

Integrating Angular Frontend with Laravel Sanctum Auth

May 19, 2025 |

10 minutes read

Integrating AngularFrontend with LaravelSanctum Auth 1 (1)

With Angular and Laravel Sanctum Secure SPA Authentication

Combining Angular and Laravel Sanctum is a good blend to build secure web applications with a touch of contemporariness. Laravel Sanctum offers a light-weight authentication package for single-page applications (SPAs), while Angular offers a dynamic front-end framework. When put together, they make the front-end to back-end communication silky smooth, thus making user interaction smoother and secure.

In this step-by-step tutorial, we are going to detail the process of combining Angular and Laravel Sanctum. We will walk you through setting up the Laravel backend using Sanctum, setting up the Angular frontend, and building secure authentication pipelines. If you are an Angular Development Company or searching for Angular Development Services, this tutorial would be beneficial for you.

Setting Up Angular and Laravel with Sanctum

1. Install Laravel

Begin by creating a new Laravel project:

composer create-project –prefer-dist laravel/laravel laravel-sanctum-api

2. Install Sanctum

Add Sanctum to your Laravel project:
composer require laravel/sanctum
Publish the Sanctum configuration:

php artisan vendor: publish– provider=”Laravel\Sanctum\SanctumServiceProvider”

Run migrations to create the necessary tables:

php artisan migrate

3. Configure Sanctum Middleware

In app/Http/Kernel.php, add Sanctum’s middleware to the api middleware group:
‘api’ => [
    \Laravel\Sanctum\Http\Middleware\EnsureFrontendRequestsAreStateful::class,
    ‘throttle:api’,
    \Illuminate\Routing\Middleware\SubstituteBindings::class,
],

4. Update User Model

In app/Models/User.php, include the HasApiTokens trait:

use Laravel\Sanctum\HasApiTokens;
class User extends Authenticatable
{
    use HasApiTokens, HasFactory, Notifiable;
}

5. Set Up Authentication Routes

In routes/api.php, define routes for registration and login:

use App\Http\Controllers\Api\AuthController;

Route::post(‘/register’, [AuthController::class, ‘register’]);
Route::post(‘/login’, [AuthController::class, ‘login’]);
Route::middleware(‘auth:sanctum’)->get(‘/user’, function (Request $request) {

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

6. Create Authentication Controller

Generate a controller:
php artisan make: controller Api/AuthController
Implement registration and login methods in AuthController.php:
namespace App\Http\Controllers\Api;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\User;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Auth;
class AuthController extends Controller
{
    public function register(Request $request)
    {
        $request->validate([
            ‘name’ => ‘required|string’,
            ’email’ => ‘required|email|unique:users’,
            ‘password’ => ‘required|string|confirmed’,
        ]);
        $user = User::create([
            ‘name’ => $request->name,
            ’email’ => $request->email,
            ‘password’ => Hash::make($request->password),
        ]);
        return response()->json([‘message’ => ‘User registered successfully.’]);
    }
    public function login(Request $request)
    {
        if (!Auth::attempt($request->only(’email’, ‘password’))) {
            return response()->json([‘message’ => ‘Invalid credentials.’], 401);
        }
        $token = $request->user()->createToken(‘auth_token’)->plainTextToken;
        return response()->json([‘access_token’ => $token, ‘token_type’ => ‘Bearer’]);
    }
}

Configuring Angular Frontend

1. Create an Angular Project

Generate a new Angular application:
new angular-sanctum-app
cd angular-sanctum-app

2. Install Dependencies

Install necessary packages:
npm install axios

3. Set Up Authentication Service

Create a service to handle authentication:

ng generate service auth

In auth.service.ts, implement methods for registration and login:(Laracasts)
import { Injectable } from ‘@angular/core’;
import axios from ‘axios’;
@Injectable({
  providedIn: ‘root’
})

export class AuthService {

  private apiUrl = ‘http://localhost:8000/api’;
  async register(userData: any) {
    return await axios.post(`${this.apiUrl}/register`, userData);
  }
  async login(credentials: any) {
    return await axios.post(`${this.apiUrl}/login`, credentials);
  }
}

4. Handle CSRF Protection

Before making authentication requests, retrieve the CSRF token:

await axios.get(‘http://localhost:8000/sanctum/csrf-cookie’);

This ensures that Laravel’s CSRF protection is satisfied.

5. Implement Authentication Components

Create components for registration and login:

ng generate component register

ng generate component login

In these components, utilize the AuthService to handle user interactions.

Ensuring Secure Communication

1. Configure CORS

In Laravel, set up CORS in config/cors.php:
‘paths’ => [‘api/*’, ‘sanctum/csrf-cookie’],
‘allowed_methods’ => [‘*’],
‘allowed_origins’ => [‘http://localhost:4200’],
‘allowed_headers’ => [‘*’],
‘supports_credentials’ => true,

2. Update .env File

Set the frontend URL in .env:

SANCTUM_STATEFUL_DOMAINS=localhost:4200

SESSION_DOMAIN=localhost

3. Use HttpOnly Cookies

Laravel Sanctum uses HttpOnly cookies for authentication, enhancing security by preventing JavaScript access to the cookie.

Secure Your SPA with Angular & Laravel Sanctum

The Way Forward

Combining Angular with Laravel Sanctum is a safe and effective way of dealing with authentication in contemporary web applications. Developers can aid in seamless communication between the frontend and backend as well as unlock the maximum capacity of both frameworks using the above steps. In case other users require professional help in this combination, they can hire a Laravel Development Company or Laravel Developers for added guidance and support.

Free Consultation

    Kinjal Patel

    Kinjal Patel is one of the very prominent & experienced working professionals holding a strong 12-year project management career in the interest of Magento, Shopify, Prestashop at iFlair Web Technologies Pvt. Ltd. Kinjal shines up as a senior project manager while coming up with fresh online solutions and ensuring on-time project delivery by driving customer happiness. Kinjal, in his strategic planning along with team-leading expertise, successfully manages various projects with perfect team coordination and error-free output quality.



    MAP_New

    Global Footprints

    Served clients across the globe from38+ countries

    iFlair Web Technologies
    Privacy Overview

    This website uses cookies so that we can provide you with the best user experience possible. Cookie information is stored in your browser and performs functions such as recognising you when you return to our website and helping our team to understand which sections of the website you find most interesting and useful.