1

Why does my csrf token expires as soon as I try to use it?

I'm having a weird problem with the XSRF token and session token I receive and send back with Angular.

When I make a request to the endpoint sanctum/csrf, I do get a XSRF-TOKEN and SESSION-TOKEN with a 2h lifetime as a response. But on subsequent request to a laravel route, the tokens I send are set to be expired the moment I received them? Resulting in a "csrf toekn mismatch" error. The tokens I receive and the ones I use in further requests are indeed the same. But the expiration time changes it seems. I'm lost there...

constructor(private testService: TestService, private http: HttpClient) { }

  ngOnInit(): void {
    this.http.get('http://localhost:8000/sanctum/csrf-cookie', { withCredentials: true }).subscribe(() => {

      console.log('CSRF cookie set.');

      this.http.post('http://localhost:8000/api/login', {
        email: 'exemple@gmail.com',
        password: 'exemple-'
      }, { withCredentials: true }).subscribe((response) => {

        console.log(response);

        this.http.get('http://localhost:8000/api/user', { withCredentials: true }).subscribe((response => {
          console.log(response);
        }));

      });

this is the code I'm using. The first get method sends me the token, 2h lifetime. The next post method uses the tokens, but the expire date is set to the exact time I received it. I guess the "csrf token mismatch" error I get comes from this.

Any clue?

Kms
  • 1,082
  • 2
  • 11
  • 27
Velwitch
  • 21
  • 5
  • Do you mean that you're trying to use the same token twice, and the second time it is marked as expired? If so, that's probably deliberate, to protect against attackers tricking users into repeating an action. – IMSoP May 07 '23 at 13:01
  • on the post method to login I use { withCredentials: true } to add the token in my cookies to the request, since the endpoint requires a csrf token. But apparently the one I use expires immediatly when I received it from the previous get method. – Velwitch May 07 '23 at 13:07
  • The error is on the http://localhost:8000/api/login request, sending me 419 error, "csrf token mismatch". Even though the token attached to the request is the same I received from the 'http://localhost:8000/sanctum/csrf-cookie' endpoint response. Only thing beeing that the token is alredy expired when I use it... – Velwitch May 07 '23 at 13:13
  • Changed the token lifetime. Now the expiration date is good. Still get the token mismatch though... – Velwitch May 07 '23 at 13:33

1 Answers1

1

Ok so the problem was that Anuglar does NOT add the necessary header with the csrf-token, like the sanctum doc says. You need an interceptor to add the right X-XSRF-TOKEN header to your request, and give it the value of the token you received.

CSRF token mismatch Laravel sanctum and Angular http

The top answer helped me (don't forget to change your app.module accordingly).

Velwitch
  • 21
  • 5