Laravel 11 Sanctum Authentification not working with Angular 18.

Updated: Jan 25, 2025

Laravel 11 Sanctum Authentification not working with Angular 18.

To answer your question, let me first clarify that as of now, Laravel 11 does not exist, and Sanctum is the default authentication system in Laravel 8 and above. Angular 18 is also not released yet, so we will assume you are using the latest stable versions of Laravel 8 and Angular 11 for this answer.

When setting up Laravel Sanctum with Angular, there are a few things to keep in mind to ensure a smooth authentication workflow. Here's a step-by-step guide to help you get started:

  1. Set up Laravel Sanctum: a. Install Laravel Sanctum using Composer: composer require laravel/sanctum b. Add SanctumServiceProvider::class to the providers array in config/app.php. c. Run the migration to create the sanctum_tokens table: php artisan migrate. d. Set the SANCTUM_STATEFUL environment variable to true in the .env file.

  2. Set up Angular: a. Install Angular CLI: npm install -g @angular/cli. b. Create a new Angular project: ng new my-project. c. Install HttpClient: ng add @angular/common/http.

  3. Configure Angular to work with Laravel Sanctum: a. Create a new file auth.interceptor.ts in the src/interceptors folder. b. Implement the HttpInterceptor interface and add the doIntercept method. c. In the doIntercept method, check if the request is an authentication request and add the Authorization header with the token from the localStorage. d. Register the interceptor in the app.module.ts file.

  4. Set up Angular to make API requests: a. Create a new file api.service.ts in the src/services folder. b. Implement the HttpClient methods to make API requests. c. Inject the HttpClient in the api.service.ts file.

  5. Set up Angular to handle authentication responses: a. Create a new file auth.service.ts in the src/services folder. b. Implement the methods to handle authentication responses, such as login, logout, and checking if the user is authenticated. c. Inject the HttpClient and the Router in the auth.service.ts file.

  6. Set up Angular to protect routes: a. In the app-routing.module.ts file, add the CanActivate guard to the routes that need to be protected. b. Inject the AuthService in the CanActivate guard and check if the user is authenticated before allowing access to the route.

  7. Test the authentication workflow: a. Make an API request to the Laravel server to log in. b. Check if the user is authenticated in Angular. c. Access a protected route in Angular.

Here's a sample code for the auth.interceptor.ts file:

import { Injectable } from '@angular/core';
import { HttpEvent, HttpHandler, HttpInterceptor, HttpRequest } from '@angular/common/http';
import { Observable } from 'rxjs';
import { tap } from 'rxjs/operators';

@Injectable()
export class AuthInterceptor implements HttpInterceptor {
  intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    const token = localStorage.getItem('token');

    if (token) {
      request = request.clone({
        setHeaders: {
          Authorization: `Bearer ${token}`
        }
      });
    }

    return next.handle(request).pipe(
      tap(response => {
        // Handle successful response here
      }, error => {
        // Handle error response here
      })
    );
  }
}

I hope this helps you get started with setting up Laravel Sanctum authentication with Angular 11. Let me know if you have any questions or need further clarification.