what is CSRF Protection in laravel

Answer

Laravel makes it easy to protect your application from cross-site request forgeries. Cross-site request forgeries are a type of malicious exploit whereby unauthorized commands are performed on behalf of the 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.

Insert The CSRF Token Into A Form

<input type="hidden" name="_token" value="<?php echo csrf_token(); ?>">

Of course, using the Blade templating engine:

<input type="hidden" name="_token" value="{{ csrf_token() }}">

You do not need to manually verify the CSRF token on POST, PUT, or DELETE requests. The VerifyCsrfToken HTTP middleware will verify token in the request input matches the token stored in the session.

X-CSRF-TOKEN

In addition to looking for the CSRF token as a "POST" parameter, the middleware will also check for the X-CSRF-TOKEN request header. You could, for example, store the token in a "meta" tag and instruct jQuery to add it to all request headers:

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

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

Now all AJAX requests will automatically include the CSRF token:

$.ajax({
   url: "/foo/bar",
})

X-XSRF-TOKEN

Laravel also stores the CSRF token in a XSRF-TOKEN cookie. You can use the cookie value to set the X-XSRF-TOKEN request header. Some JavaScript frameworks, like Angular, do this automatically for you.

All laravel Questions

Ask your interview questions on laravel

Write Your comment or Questions if you want the answers on laravel from laravel Experts
Name* :
Email Id* :
Mob no* :
Question
Or
Comment* :
 





Disclimer: PCDS.CO.IN not responsible for any content, information, data or any feature of website. If you are using this website then its your own responsibility to understand the content of the website

--------- Tutorials ---