Integrating Angular Frontend with Laravel Sanctum Auth May 19, 2025 | 10 minutes read 3 Likes With Angular and Laravel Sanctum Secure SPA AuthenticationCombining 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 Sanctum1. Install LaravelBegin by creating a new Laravel project:composer create-project –prefer-dist laravel/laravel laravel-sanctum-api2. Install SanctumAdd 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 migrate3. Configure Sanctum MiddlewareIn 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 ModelIn app/Models/User.php, include the HasApiTokens trait:use Laravel\Sanctum\HasApiTokens; class User extends Authenticatable { Â Â Â Â use HasApiTokens, HasFactory, Notifiable; }5. Set Up Authentication RoutesIn 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 ControllerGenerate 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 Frontend1. Create an Angular ProjectGenerate a new Angular application: new angular-sanctum-app cd angular-sanctum-app2. Install DependenciesInstall necessary packages: npm install axios3. Set Up Authentication ServiceCreate a service to handle authentication:ng generate service authIn 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 ProtectionBefore 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 ComponentsCreate components for registration and login:ng generate component registerng generate component loginIn these components, utilize the AuthService to handle user interactions. Ensuring Secure Communication1. Configure CORSIn 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 FileSet the frontend URL in .env:SANCTUM_STATEFUL_DOMAINS=localhost:4200SESSION_DOMAIN=localhost3. Use HttpOnly CookiesLaravel Sanctum uses HttpOnly cookies for authentication, enhancing security by preventing JavaScript access to the cookie. Secure Your SPA with Angular & Laravel Sanctum Get GuideThe Way ForwardCombining 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 Angular Development ServicesLaravel Development CompanyAngular Development CompanyHire Laravel DevelopersBest Laravel Development CompanyLaravel DevelopersAngular and LaravelLopa DasMay 19 2025With over 13 years of experience, Lopa Das is a seasoned professional at iFlair Web Technologies Pvt Ltd, specializing in web and mobile app development. Her technical expertise spans across Laravel, PHP, CodeIgniter, CakePHP, React, Vue.js, Nuxt.js, iOS, Android, Flutter, and React Native. Known for her exceptional skills in team handling, client communication, presales, and risk analysis, Lopa ensures seamless project execution from start to finish. Her proficiency in Laravel CRM, Next.js, and mobile app development makes her a valuable asset in delivering robust, scalable solutions.You may also like Optimizing Global Logistics through Magento E-Commerce Development Services Read More Oct 17 2025 Building Robust Applications: Simplified State Management with NgRx Read More Oct 16 2025 Choosing the Right Angular UI Library: Angular Material, PrimeNG, and NG-ZORRO Compared Read More Oct 14 2025 From Code Bloat to Clean Architecture: Problem-Solving Approaches in Angular Applications Read More Sep 05 2025 Transforming Complex Ideas into Reality with a Laravel Development Agency Read More Aug 06 2025 Modular Frontend Architecture by a Leading Angular Development Company Read More Jul 31 2025