0
votes

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.

3
Does this answer your question? angular4 httpclient csrf does not send x-xsrf-token - John
I don't know where to find the value for headerName . HttpClientXsrfModule.withOptions({ headerName: 'What should it be here??' }) - O Connor

3 Answers

0
votes

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!

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

create a interceptor for every reqst u add xsrf token

@Injectable() export class HttpXsrfInterceptor implements HttpInterceptor {  constructor(private tokenExtractor: HttpXsrfTokenExtractor) {}intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {const headerName = 'X-XSRF-TOKEN'; let token = this.tokenExtractor.getToken() as string; if (token !== null && !req.headers.has(headerName)) {      req = req.clone({ headers: req.headers.set(headerName, token) });}    return next.handle(req);}}