How To Use CSRF Tokens With Laravel

Very often with a Laravel application you will have some type of CRUD (Create, Read, Update, Delete). This, of course requires HTML forms and submitting data from the front-end to the back end controllers. Laravel uses CSRF tokens to add another layer of security on top of your web application. If the CSRF token is missing during form submission or likewise, Laravel will complain about it.


In this following tutorial guide, a few different ways of how you can place the CSRF token into your pages effectively we be explored.


Method 1 – Adding the CSRF Token Meta Tag

Adding CSRF token into the head section of your HTML.


Generally, this method will be coded into the Layouts/Header file or similar.


Add the following code to your file

<meta name="csrf-token" content="{{ csrf_token() }}">

This will yield something like the following when the page is rendered.

<meta name="csrf-token" content="t0l2x6ggZmd06aL8Mo4Wv6bQPQOAP0vPYZlyBjFK">


Method 2 – Adding the CSRF Token Input Field

Next, if your submitting data via a form, Laravel expects to see a _token field within JSON that is submitted to the controller. This token will be validated specifically for your application to enhance the security cross-site requests.


Let’s take a form.

<form method="post" action="{{ route('mycontroller.create') }}" >
<label for="Name">Name</label>
<input type="text" class="form-control" name="name"/>
<button type="submit" class="btn btn-primary">Add Macro</button>
</form>

If this form was submitted, Laravel would stop the request as there is no CSRF token present.


All’s we need to do is add the following Laravel blade syntax

@csrf

Yep, that simple.


So, in full this would look like the following

<form method="post" action="{{ route('mycontroller.create') }}" >
    @csrf
    <label for="Name">Name</label>
    <input type="text" class="form-control" name="name"/>
    <button type="submit" class="btn btn-primary">Add Macro</button></form>

This would yield something like the following

<form method="post" action="http://localhost/mycontroller/create" ><input type="hidden" name="_token" value="t0l2x6ggZmd06aL8Mo4Wv6bQPQOAP0vPYZlyBjFK">
<label for="Name">Name</label>
<input type="text" class="form-control" name="name"/>
<button type="submit" class="btn btn-primary">Add Macro</button></form>

And now, when this form is submitted, the token would be validated successfully and the data would pass to the controller fluently.


Source: paper.li

0 comments

Recent Posts

See All