Laravel 11 Sanctum Authentification not working with Angular 18

Discussão em 'Angular' iniciado por Youssera Zoukha MECIFI, Janeiro 21, 2025.

  1. I'm trying to implement Sanctum authentification between laravel 11 and Angular 18 but to no eval, i tried everything i could find on forums , tutorials , chatgpt but nothing worked , this website is my last hope So my problem is that after submiting the login form i get redirected to the dashboard page with a success message but i get instantly logged out, it's like i never been logged even though i cant see the cookies laravel_session & XSRF-TOKEN being created in the Application tab of my devtools,so when ever i got to /user route or any other route protected with middleware('auth:sanctum') i get Unauthenticated error i dont understand what i did wrong Here is my cors.php file:

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

    'allowed_methods' => ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'],

    'allowed_origins' => [env('FRONTEND_URL', 'http://localhost:4200')],

    'allowed_origins_patterns' => [],

    'allowed_headers' => ['Content-Type', 'X-Requested-With', 'Accept-Language','Authorization', 'X-XSRF-TOKEN', 'X-CSRF-TOKEN', 'Accept', 'Origin', 'User-Agent'],

    'exposed_headers' => [],

    'max_age' => 7200,

    'supports_credentials' => true,


    here is my .env file :

    APP_NAME="Notaires Ain Seba"
    APP_NAME_ARABE="مكتب الموثقين عين السبع"
    APP_ENV=local
    APP_KEY=base64:DkIbEgZ6QFMXiULRCMN1u6BILsi4NhYEL8rmkpRfUVg=
    APP_DEBUG=true
    APP_TIMEZONE=UTC
    APP_URL=http://localhost:8000
    FRONTEND_URL=http://localhost:4200

    SANCTUM_STATEFUL_DOMAINS=localhost:4200
    SESSION_DRIVER=database
    SESSION_LIFETIME=120
    SESSION_PATH=/
    SESSION_DOMAIN=.localhost
    SESSION_SECURE_COOKIE=false


    and for my Angular code; i made an interceptor:

    import { HttpInterceptorFn } from '@angular/common/http';

    export const httpTokenInterceptor: HttpInterceptorFn = (req, next) => {
    const xsrfToken = getCookie('XSRF-TOKEN'); // Fetch XSRF-TOKEN from cookies

    if (xsrfToken) {
    req = req.clone({
    withCredentials: true, // Ensure cookies are sent
    setHeaders: {
    'Accept': 'application/json',
    'X-XSRF-TOKEN': xsrfToken,
    },
    });

    } else {
    console.warn('No XSRF Token found in cookies.');
    }

    return next(req);
    };

    /**
    * Utility function to get cookies by name
    */
    function getCookie(name: string): string | null {
    try {
    const cookies = document.cookie.split('; ');

    for (const cookie of cookies) {
    const [key, value] = cookie.split('=');
    if (key === name) {
    return decodeURIComponent(value);
    }
    }
    } catch (error) {
    console.error('Error retrieving cookie:', error);
    }

    return null;
    }


    and here is my authentification service:

    /* eslint-disable @typescript-eslint/no-explicit-any */
    import { HttpClient, HttpHeaders } from '@angular/common/http';
    import { Injectable } from '@angular/core';
    import { BehaviorSubject, Observable } from 'rxjs';
    import { tap } from 'rxjs/operators';
    import { environment } from 'src/environments/environment';

    @Injectable({
    providedIn: 'root',
    })
    export class HttpTokenService {
    private baseUrl: string = environment.apiUrl;
    public headers = this.getHeaders();

    private isLoggedInSubject = new BehaviorSubject<boolean>(false); // Default state: logged out
    public isLoggedIn$ = this.isLoggedInSubject.asObservable();

    constructor(private http: HttpClient) { }

    private getHeaders(): HttpHeaders {
    const language = localStorage.getItem('lang') || 'Ar';

    return new HttpHeaders({
    'Accept-Language': language // Attach language header
    });
    }


    getCsrfToken(): Observable<any> {
    return this.http.get(`${this.baseUrl}/sanctum/csrf-cookie`, { withCredentials: true, observe: 'response' });
    }

    login(data: any): Observable<any> {
    return this.http.post(`${this.baseUrl}/login`, data, { withCredentials: true, headers: this.headers })
    .pipe(
    tap(() => this.isLoggedInSubject.next(true)) // Update state on successful login
    );
    }

    logout(): Observable<any> {
    return this.http.post(`${this.baseUrl}/logout`, {}, { withCredentials: true, headers: this.headers })
    .pipe(
    tap(() => this.isLoggedInSubject.next(false)) // Update state on successful logout
    );
    }


    also since there is no app.module file in this version here is where i declared the interceptor: file main.ts :

    bootstrapApplication(AppComponent, {
    providers: [
    // Angular modules and other providers
    importProvidersFrom(BrowserModule, AppRoutingModule),
    provideAnimations(),
    provideHttpClient(
    withInterceptors([httpTokenInterceptor]),
    withXsrfConfiguration({
    cookieName: 'XSRF-TOKEN', // Cookie name where the token is stored
    headerName: 'X-XSRF-TOKEN', // Header name to send the token
    })
    ),
    ]
    }).catch((err) => console.error(err));


    please someone try to help me i've been desperate for many days

    Continue reading...

Compartilhe esta Página