0

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.

O Connor
  • 4,236
  • 15
  • 50
  • 91
  • Does this answer your question? [angular4 httpclient csrf does not send x-xsrf-token](https://stackoverflow.com/questions/46040922/angular4-httpclient-csrf-does-not-send-x-xsrf-token) – John Apr 12 '21 at 11:14
  • I don't know where to find the value for `headerName` . HttpClientXsrfModule.withOptions({ headerName: 'What should it be here??' }) – O Connor Apr 12 '21 at 15:30

2 Answers2

0

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!

ImVk
  • 41
  • 1
  • Sending XSRF token : 1.You can create a new route to show the csrf token using your controller with help of the function below. ( ... 2.Select the Body tab on postman and then choose x-www-form-urlencoded. 3.Copy the token and paste in postman as the value of the key named _token. 4.Execute your post request on your URL/Endpoint. – ImVk Apr 12 '21 at 11:55
  • I cannot follow you, why do you talk about using postman. I already have a working API end point, no need to use Postman to test the API url end point. What I want to know is how to set X-XSRF-TOKEN in the API Request Headers in Angular 4, 5, 9 or 11. – O Connor Apr 14 '21 at 14:35
0
imports: [ HttpClientModule,HttpClientXsrfModule.withOptions({cookieName: 'My-Xsrf-Cookie',headerName: 'My-Xsrf-Header'})]; // headerName is optional
My Stack Overfloweth
  • 4,729
  • 4
  • 25
  • 42
ImVk
  • 41
  • 1