CSRF Protection In Laravel And Why We Need This

In this tutorial we will know about CSRF Protection in Laravel . Why do you use csrf token in your laravel app ? in this lesson we are going to know about it. 

Laravel makes it easy to protect your application from cross-site request forgery (CSRF) attacks. Cross-site request forgeries are a type of malicious exploit whereby unauthorized commands are performed on behalf of an authenticated user.

Laravel automatically generates a CSRF "token" for each active user session managed by the application. This token is used to verify that the authenticated user is the one actually making the requests to the application.

Anytime you define an HTML form in your application, you should include a hidden CSRF token field in the form so that the CSRF protection middleware can validate the request. You may use the @csrf Blade directive to generate the token field:

csrf-token-in-laravel

CSRF Protection in Laravel

 

The VerifyCsrfToken middleware, which is included in the web middleware group will automatically verify that the token in the request input matches the token stored in the session.

CSRF Tokens & JavaScript

When building JavaScript-driven applications, it is convenient to have your JavaScript HTTP library automatically attach the CSRF token to every outgoing request. By default, the resources/js/bootstrap.js file registers the value of the csrf-token meta tag with the Axios HTTP library. If you are not using this library, you will need to manually configure this behavior for your application.

 

Setup Ajax with CSRF Tokens

In addition to checking for the CSRF token as a POST parameter, the VerifyCsrfTokenmiddleware will also check for the X-CSRF-TOKEN request header. You could, for example, store the token in an HTML meta tag:

 

Then, once you have created the meta tag, you can instruct a library like jQuery to automatically add the token to all request headers. This provides simple, convenient CSRF protection for your AJAX based applications:

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

 

Recommended: How to Disable CSRF Token Protection on Routes Example

 

Hope it can help you.

 

#laravel #csrf-token #csrf-protection