How to use symfony csrf tokens with react.js?

Member

by jerad , in category: PHP Frameworks , 2 months ago

How to use symfony csrf tokens with react.js?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by darrion.kuhn , 2 months ago

@jerad 

When using Symfony CSRF tokens with React.js, you'll need to make a small adjustment to pass the token from the Symfony backend to the React frontend.


Here's how you can implement it:

  1. In your Symfony backend, generate the CSRF token as usual:
1
2
3
4
5
6
7
8
use SymfonyComponentSecurityCsrfCsrfTokenManagerInterface;

public function yourControllerAction(CsrfTokenManagerInterface $csrfTokenManager)
{
    $token = $csrfTokenManager->getToken('token_id');
    // Return the token to the React frontend
    return $this->json(['token' => $token->getValue()]);
}


  1. In your React frontend component, make an API request to fetch the CSRF token:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
import axios from 'axios';

axios.get('/your-symfony-endpoint-to-fetch-csrf-token')
  .then(response => {
    const csrfToken = response.data.token;
    // Store the CSRF token in the state or in a context for later use
    this.setState({ csrfToken });
  })
  .catch(error => {
    // Handle error
  });


  1. Use the CSRF token when making a request from React to your Symfony backend:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
axios.post('/your-symfony-endpoint', { data }, {
  headers: {
    'X-CSRF-Token': this.state.csrfToken, // Add the CSRF token to headers
  },
})
  .then(response => {
    // Handle response
  })
  .catch(error => {
    // Handle error
  });


  1. In your Symfony backend, validate the CSRF token as usual:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
use SymfonyComponentSecurityCsrfCsrfToken;
use SymfonyComponentSecurityCsrfCsrfTokenManagerInterface;
use SymfonyComponentSecurityCsrfExceptionInvalidCsrfTokenException;

public function yourControllerAction(Request $request, CsrfTokenManagerInterface $csrfTokenManager)
{
    $token = new CsrfToken('token_id', $request->headers->get('X-CSRF-Token'));

    if (!$csrfTokenManager->isTokenValid($token)) {
        throw new InvalidCsrfTokenException('Invalid CSRF token.');
    }

    // Continue processing the request
}


With this approach, you can handle CSRF protection using Symfony's CSRF tokens in your React.js frontend.