Cross Site Request Forgery

    The CsrfComponent works by setting a cookie to the user’s browser. When formsare created with the , a hidden fieldis added containing the CSRF token. During the Controller.startup event, ifthe request is a POST, PUT, DELETE, PATCH request the component will compare therequest data & cookie value. If either is missing or the two values mismatch thecomponent will throw aCake\Network\Exception\InvalidCsrfTokenException.

    Note

    You should always verify the HTTP method being used before executing to avoidside-effects. You should oruse Cake\Http\ServerRequest::allowMethod() to ensure the correctHTTP method is used.

    Deprecated since version 3.5.0: You should use instead of.

    Simply by adding the CsrfComponent to your components array,you can benefit from the CSRF protection it provides:

    Settings can be passed into the component through your component’s settings.The available configuration options are:

    • cookieName The name of the cookie to send. Defaults to csrfToken.
    • Whether or not the cookie will be set with the Secure flag. That is,the cookie will only be set on a HTTPS connection and any attempt over normal HTTPwill fail. Defaults to false.
    • field The form field to check. Defaults to _csrfToken. Changing thiswill also require configuring FormHelper.
      When enabled, you can access the current CSRF token on the request object:

    Note

    When using the CsrfComponent you should always start your forms with theFormHelper. If you do not, you will need to manually create hidden inputs ineach of your forms.

    In addition to request data parameters, CSRF tokens can be submitted througha special X-CSRF-Token header. Using a header often makes it easier tointegrate a CSRF token with JavaScript heavy applications, or XML/JSON based APIendpoints.