Skip to main content
Version: 4.x

CSRF Protection in BowPHP

Introduction​

Bow makes it easy to protect your application against 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.

Bow 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.

Whenever 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:

<form method="POST" action="/upload">
{{{ csrf_field() }}}
...
</form>

The App\Middlewares\ClientCsrfMiddleware::class middleware, which is included in the Web middleware group, automatically verifies 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.

The CSRF middleware is automatically added when each request is executed.

X-CSRF-TOKEN​

In addition to checking the CSRF token as a POST parameter, the App\Middlewares\ClientCsrfMiddleware::class middleware also checks the X-CSRF-TOKEN request header. You can, for example, store the token in an HTML META tag:

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

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')
}
});

X-XSRF-TOKEN​

Bow stores the current CSRF token in an XSRF-TOKEN cookie that is included in every response generated by the Framework. You can use the cookie value to set the X-XSRF-TOKEN request header.

This cookie is primarily sent as a convenience, since some JavaScript frameworks and libraries, such as Angular and Axios, automatically place its value in the X-XSRF-TOKEN header.

Is something missing?

If you run into problems with the documentation or have suggestions to improve the documentation or the project in general, please open an issue for us, or send a tweet mentioning the Twitter account @bowframework or directly on github.