In this episode, we dive into actually integrating our cross-site request forgery (CSRF) tokens into our forms, now that we've got the middleware set up. At first, we explore how to pass the necessary CSRF token keys and values from our controller down to the template, but quickly realize this can get repetitive and messy if we do it everywhere we need a form.
To make things easier, we create a helper function in our Twig runtime extension. This function automatically generates and outputs the right hidden input fields needed for CSRF protection, using values from our CSRF guard class. We go through setting up the helper, calling the appropriate methods to get both the token name and value, and explain how each piece fits together. We also touch on outputting these values raw in Twig so they render correctly in our HTML.
After testing the implementation in the navigation, we extend this to our login and registration forms, ensuring they're now protected too. The end result: our forms are now nicely secured against CSRF attacks, and we've kept our code clean and DRY by using a smart helper function.