Laravel xsrf-token httponly

Laravel XSRF-TOKEN httponly

The Laravel framework provides built-in protection against Cross-Site Request Forgery (CSRF) attacks. By default, Laravel generates a unique CSRF token for each user session and includes it in the form data or headers for non-GET requests. This token is used to verify that the authenticated user is the one actually making the requests.

In order to enhance the security of the CSRF token, Laravel allows you to configure it to be marked as httponly, which means it will not be accessible to JavaScript code running within the client’s browser. This protects against certain types of attacks, such as cross-site scripting (XSS), where an attacker tries to steal the token using malicious JavaScript code.

To enable the XSRF-TOKEN to be marked as httponly, you need to modify the Laravel configuration file (config/session.php). Set the ‘http_only’ option to true:

'http_only' => true,

After making this change and clearing your Laravel session, the XSRF-TOKEN will be sent as a cookie with the httponly flag. This means that it cannot be accessed by JavaScript code running in the browser, effectively protecting it from being stolen by XSS attacks.

Example

Let’s say you have a Laravel application with a form that submits data using the POST method. When rendering the form, you can include the CSRF token as a hidden input field:

<form method="POST" action="/submit">
  @csrf
  <!-- other form fields -->
  </form>

The “@csrf” directive generates the CSRF token and includes it as a hidden input field. On form submission, the token will be sent along with the other form data.

In your server-side code, you can validate the CSRF token using the “csrf” middleware provided by Laravel. If the token is invalid or missing, Laravel will automatically return a 419 “Page Expired” error:

public function submitForm(Request $request)
{
  $request->validate([
    '_token' => 'required|csrf',
    // other validation rules
  ]);
  // process the form data
}

By adding the “csrf” validation rule, Laravel will ensure that the CSRF token is present in the request and matches the one generated for the session. If not, the validation will fail, and you can handle it accordingly.

Read more

Leave a comment