How to set XSRF-TOKEN in Angular 11 API request header in Laravel 8?

1.2k views Asked by At

I integrate Angular (11) frontend within the Laravel 8 application. For making API requests, users are logged in. Every time the frontend Angular makes a request to the backend API, I get the following error:

Status Code: 401 Unauthorized

I have set up VueJs frontend to test the same API endpoint URL and VueJs can reach the API endpoint and get response back from the backend as well. When I compare the Request Headers of the API request making by VueJS with the request making by Angular 11, I see that the Request Headers of Angular 11 does not have X-XSRF-TOKEN. So I think that is the reason why I get the above error.

Below is how VueJs and AXIOS are setup within Laravel 8 to have the X-XSRF-TOKEN in the API Request Headers.

window.axios = require('axios');
window.axios.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';
const token = document.head.querySelector('meta[name="csrf-token"]');

if (token) {
    window.axios.defaults.headers.common["X-CSRF-TOKEN"] = token.content;
}

How to set the X-XSRF-TOKEN or X-CSRF-TOKEN in the API Request Headers making by Angular 11 within Laravel 8?

Note: Angular 11 frontend and VueJs frontend are both integrated on the frontend web page of the Laravel 8 application, thus they are on the same domain. So I think laravel-cors package is not needed.

2

There are 2 answers

2
ImVk On

To obtain the XSRF token, you has to use a non-modifying HTTP method containing header X-CSRF-Token with the value Fetch . The token is issued only if the user has already been authenticated. If the user has not been authenticated , any request with a modifying method is rejected by this filter. For more info about XSRF protection Click here!

1
ImVk On
imports: [ HttpClientModule,HttpClientXsrfModule.withOptions({cookieName: 'My-Xsrf-Cookie',headerName: 'My-Xsrf-Header'})]; // headerName is optional