> ## Documentation Index
> Fetch the complete documentation index at: https://inertiajs-vi.tuantq.online/llms.txt
> Use this file to discover all available pages before exploring further.

# Bảo vệ CSRF

## Thực hiện request

Laravel tự động thêm CSRF token phù hợp khi thực hiện request qua Inertia hoặc Axios. Tuy nhiên, nếu dùng Laravel, hãy nhớ bỏ thẻ meta `csrf-token` khỏi dự án vì thẻ này sẽ ngăn CSRF token được làm mới đúng cách.

Nếu framework phía máy chủ có bảo vệ cross-site request forgery (CSRF), bạn cần đảm bảo mỗi request Inertia đều chứa CSRF token cần thiết cho `POST`, `PUT`, `PATCH` và `DELETE`.

Một số server-side framework như Laravel tự động đưa CSRF token vào request. Khi dùng các framework này, bạn không cần cấu hình bổ sung.

Tuy nhiên, nếu cần tự xử lý bảo vệ CSRF, một cách là gửi CSRF token dưới dạng prop trong mọi response. Sau đó bạn có thể sử dụng token này khi thực hiện request Inertia.

<CodeGroup>
  ```js Vue icon="vuejs" theme={null}
  import { router, usePage } from "@inertiajs/vue3";

  const page = usePage();

  router.post("/users", {
    _token: page.props.csrf_token,
    name: "John Doe",
    email: "john.doe@example.com",
  });
  ```

  ```js React icon="react" theme={null}
  import { router, usePage } from "@inertiajs/react";

  const props = usePage().props;

  router.post("/users", {
    _token: props.csrf_token,
    name: "John Doe",
    email: "john.doe@example.com",
  });
  ```

  ```js Svelte icon="s" theme={null}
  import { page, router } from "@inertiajs/svelte";

  router.post("/users", {
    _token: page.props.csrf_token,
    name: "John Doe",
    email: "john.doe@example.com",
  });
  ```
</CodeGroup>

Bạn thậm chí có thể dùng tính năng [shared data](/v3/data-props/shared-data) của Inertia để tự động đưa `csrf_token` vào mỗi response.

Một cách tốt hơn là dùng cơ chế xử lý XSRF token tích hợp sẵn của Inertia. HTTP client của Inertia tự động kiểm tra cookie `XSRF-TOKEN` và, nếu tồn tại, đưa token vào header `X-XSRF-TOKEN` cho mọi request.

Cách dễ nhất để triển khai là dùng middleware phía server. Chỉ cần đưa cookie `XSRF-TOKEN` vào mỗi response, sau đó xác minh token bằng header `X-XSRF-TOKEN` được gửi trong các request từ Inertia.

Bạn có thể tùy chỉnh tên cookie và header thông qua tùy chọn `http` trong `createInertiaApp`.

```js theme={null}
createInertiaApp({
  http: {
    xsrfCookieName: 'MY-XSRF-TOKEN',
    xsrfHeaderName: 'X-MY-XSRF-TOKEN',
  },
  // ...
})
```

## Xử lý token không khớp

Khi CSRF token không khớp, framework phía server thường ném exception dẫn đến error response. Ví dụ, Laravel ném `TokenMismatchException`, tạo ra trang lỗi `419`. Vì đây không phải response Inertia hợp lệ, lỗi sẽ được hiển thị trong modal.

<video controls className="w-full rounded-xl" src="https://mintcdn.com/tqt97/ijnwM_i4Gr-teyg5/mp4/csrf-mismatch-modal.mp4?fit=max&auto=format&n=ijnwM_i4Gr-teyg5&q=85&s=205a14b8a1512babde75e9323c04b3b0" data-path="mp4/csrf-mismatch-modal.mp4" />

Rõ ràng đây không phải trải nghiệm tốt cho người dùng. Cách xử lý tốt hơn là redirect về trang trước kèm flash message cho biết trang đã hết hạn. Kết quả sẽ là một response Inertia hợp lệ, trong đó flash message có sẵn dưới dạng prop để bạn hiển thị cho người dùng. Tất nhiên, bạn cần chia sẻ [flash message](/shared-data#flash-messages) với Inertia để cách này hoạt động.

Khi dùng Laravel, bạn có thể chỉnh exception handler của ứng dụng để tự động redirect người dùng về trang trước và flash message vào session. Bạn có thể thực hiện việc này bằng phương thức exception `respond` trong file `bootstrap/app.php`.

```php theme={null}
use Symfony\Component\HttpFoundation\Response;

->withExceptions(function (Exceptions $exceptions) {
    $exceptions->respond(function (Response $response) {
        if ($response->getStatusCode() === 419) {
            return back()->with([
                'message' => 'The page expired, please try again.',
            ]);
        }

        return $response;
    });
});
```

Kết quả là trải nghiệm tốt hơn nhiều: thay vì thấy error modal, người dùng nhận thông báo rằng trang đã hết hạn và được yêu cầu thử lại.

<video controls className="w-full rounded-xl" src="https://mintcdn.com/tqt97/ijnwM_i4Gr-teyg5/mp4/csrf-mismatch-warning.mp4?fit=max&auto=format&n=ijnwM_i4Gr-teyg5&q=85&s=04d209a2d879395a8c92fef4ef786d3c" data-path="mp4/csrf-mismatch-warning.mp4" />

***

## Tài liệu chính thức

Bài dịch này được đối chiếu từ [tài liệu Inertia.js v3 chính thức](https://inertiajs.com/docs/v3/security/csrf-protection). Nếu có khác biệt do phiên bản hoặc cập nhật mới, hãy ưu tiên tài liệu chính thức làm nguồn tham chiếu.
