X-XSRF-TOKEN header not included in headers using Angular 19

Discussão em 'Angular' iniciado por gallup gallup, Janeiro 17, 2025.

  1. In my application using Angular 19 (and ASP.NET Core 8 for the back-end), I have configured my Core module to get the XSRF cookie from the back-end on app initialization :

    import { inject, NgModule, provideAppInitializer } from '@angular/core';
    import { CommonModule } from '@angular/common';
    import { provideHttpClient, withInterceptors, withXsrfConfiguration } from '@angular/common/http';
    import { tokenInterceptor } from './interceptors/token.interceptor';
    import { AuthenticationService } from './services/authentication.service';

    export function appInitilizerCheckTokenValidity(): Promise<void> {
    const authService = inject(AuthenticationService);
    return authService.checkTokenValidity().then(
    _isValid => {},
    () => {}
    );
    }

    export function appInitilizerGetXsrfToken(): Promise<any> {
    const authService = inject(AuthenticationService);
    return authService.xsrfToken().then(
    _ => {},
    () => {}
    )
    }


    @NgModule({
    declarations: [],
    imports: [
    CommonModule
    ],
    providers: [
    provideAppInitializer(() => appInitilizerCheckTokenValidity()),
    provideAppInitializer(() => appInitilizerGetXsrfToken()),
    provideHttpClient(withXsrfConfiguration({cookieName: 'XSRF-TOKEN', headerName: 'X-XSRF-TOKEN'})),
    ]
    })
    export class CoreModule { }


    The xsrfToken() API looks like this :

    xsrfToken(): Promise<any> {
    let url = `${this.baseXsrfUrl}/xsrf`;
    return firstValueFrom(this.http.get<{elment:any}>(url));
    }


    And the API in my back-end looks like this :

    using Microsoft.AspNetCore.Http;
    using Microsoft.AspNetCore.Mvc;

    namespace AmazixWeb.Controllers
    {
    [Route("api/[controller]")]
    [ApiController]
    public class XsrfController : ControllerBase
    {
    [HttpGet("xsrf")]
    public IActionResult XSRFToken()
    {
    var csrfToken = Guid.NewGuid().ToString();
    Response.Cookies.Append("XSRF-TOKEN", csrfToken, new CookieOptions
    {
    HttpOnly = false,
    SameSite = SameSiteMode.None,
    Secure = true
    });
    return Ok();
    }
    }
    }


    On initializaion the get request to collect the XSRF cookie works fine, I receive this kind of response : [​IMG]

    At this moment Angular should take the XSRF-TOKEN cookie and place it in every headers of a POST, PUT or DELETE request (header name : X-XSRF-TOKEN) But when I make a new POST request (a POST request to login for instance), he X-XSRF-TOKEN is missing. See example below : [​IMG]

    I don't know why the X-XSRF-TOKEN header is no automatically added in the POST headers. Can someone help me please ?

    Continue reading...

Compartilhe esta Página