'In Angular CSRF/XSRF token will apply in HTML as hidden input fields?

We create Angular12 SPA's with Asp .NET core 5.0 API backend in our project. Here we implement the antiforgery XSRF/CSRF token for validation.

XSRF token works by adding in request headers to send the token and validate.

why XSRF tokens also not apply to HTML? (hidden __RequestVerificationToken values)

Startup.cs

{
    
        services.AddAntiforgery(options =>
            {
                // Set Cookie properties using CookieBuilder properties†.
                options.FormFieldName = "AntiforgeryFieldname";
                options.HeaderName = "X-XSRF-TOKEN";
                options.SuppressXFrameOptionsHeader = false;
            });
}

public void Configure(IApplicationBuilder app, IWebHostEnvironment env, IAntiforgery antiforgery)
{
app.Use(next => context =>
            {
                string path = context.Request.Path.Value;

                if (path.ToLower().Contains("/api") || string.Equals(path, "/index.html", StringComparison.OrdinalIgnoreCase))
                {
                    // The request token can be sent as a JavaScript-readable cookie, 
                    // and Angular uses it by default.
                    var tokens = antiforgery.GetAndStoreTokens(context);
                    context.Response.Cookies.Append("XSRF-TOKEN", tokens.RequestToken,
                        new CookieOptions()
                        {
                            HttpOnly = false,
                            Path = "/",
                            Secure = true,
                            SameSite = SameSiteMode.Strict


                        });
                }

                return next(context);
            });
}
//app.module.ts

HttpClientXsrfModule.withOptions({
        cookieName: 'XSRF-TOKEN',
        headerName: 'X-CSRF-TOKEN'
      })

services.ts

intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    // load token
    let xsrfToken = this.xsrfTokenExtractor.getToken();

    if (xsrfToken != null) {
      // create a copy of the request and
      // append the XSRF token to the headers list
      const authorizedRequest = req.clone({
        withCredentials: true,
        headers: req.headers.set('X-XSRF-TOKEN', xsrfToken)
      });

      return next.handle(authorizedRequest);
    } else {
      return next.handle(req);
    }
  }```


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source