Laravel CSRF Protection

In this article, we will discuss Laravel CSRF Protection. As we know, Laravel provides rich security features for a complete web application.

Let’s start the Laravel CSRF Protection in brief.

Laravel provides the easy way to protect the Laravel App from CSRF (Cross-Site Request Forgery) attack. Cross-site request forgeries are a type of malicious activity performed on behalf of an authenticated user.

In Laravel, CSRF token generated automatically with the use of some predefined blade directives. All these tokens are managed by the application for each active user session. “CSRF Token” is used to verify that the requests are made by an authenticated user.

Anytime in the Laravel development when we create the HTML form. Then we need to add a hidden CSRF token field in the form so that the default CSRF protection middleware can validate the request.

Blade directives to generate the token fields:

<form method="post" action="/formAction">

  // Latest version
  @csrf

  // Previous version
  @csrf_field

  // Or
  <input type="hidden" name="_token" value="{{ @csrf_token }}">

</form>

The predefined VerifyCsrfToken middleware located at “app/Http/Middleware” directory and included in the web middleware group will automatically verify that the token request matched with the token stored in the session.

X-CSRF-TOKEN

The predefined VerifyCsrfToken middleware also checks for the X-CSRF-TOKEN request header. For example, store the token in the HTML meta tag.

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

After creating the meta tag, we can force jQuery to use automatically add the token to all request headers. For example, adding CSRF protection to our Ajax-based applications:

$.ajaxSetup({
  headers: {
    'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
  }
});

Conclusion: In this article, we are discussing Laravel CSRF Protection. I’m trying to explain you about the Laravel CSRF tokens. So feel free to comment for any query. You can check our other Larave tutorials.

If you like our content, please consider buying us a coffee.
Thank you for your support!
Buy Me a Coffee

LaravelLaravel CSRFLaravel CSRF protectionPHP
Comments (0)
Add Comment