Home  >  Article  >  Backend Development  >  PHP Framework Security Guide: How to Prevent CSRF Attacks?

PHP Framework Security Guide: How to Prevent CSRF Attacks?

WBOY
WBOYOriginal
2024-06-01 10:36:57399browse

PHP 框架安全指南:如何防止 CSRF 攻击?

PHP Framework Security Guide: How to Prevent CSRF Attacks?

A cross-site request forgery (CSRF) attack is a type of network attack in which an attacker tricks a user into performing unintended actions within the victim's web application.

How does CSRF work?

CSRF attacks exploit the fact that most web applications allow requests to be sent between different pages within the same domain name. The attacker creates a malicious page that sends requests to the victim's application, triggering unauthorized actions.

How to prevent CSRF attacks?

1. Use anti-CSRF tokens:

  • Assign each user a unique token and store it in the session or cookie.
  • Include a hidden field in the application for submitting this token.
  • Verify that the submitted token matches the stored token.
// 生成令牌并存储在会话中
$_SESSION['csrf_token'] = bin2hex(random_bytes(32));

// 在表单中包含隐藏字段
<input type="hidden" name="csrf_token" value="<?php echo $_SESSION['csrf_token']; ?>">

// 验证提交的令牌
if (!isset($_POST['csrf_token']) || $_POST['csrf_token'] !== $_SESSION['csrf_token']) {
    // 令牌无效,拒绝请求
}

2. Use the Synchronizer Token Pattern:

  • When the page is loaded for the first time, the token is generated and It is stored in a cookie.
  • On form submission, the token is sent to the server as an HTTP header.
  • Verify that the submitted token matches the stored token.
// 在首次加载页面时生成令牌并存储在 Cookie 中
setcookie('csrf_token', bin2hex(random_bytes(32)), time() + 3600, '/');

// 在表单提交时,将令牌作为 HTTP 头发送
$headers = getallheaders();
$csrf_token = $headers['X-CSRF-Token'];

// 验证提交的令牌
if (!isset($csrf_token) || $csrf_token !== $_COOKIE['csrf_token']) {
    // 令牌无效,拒绝请求
}

Practical Case

For example, preventing CSRF attacks on fund transfers in wallets:

// 在用户加载转账页面时生成令牌
$transfer_token = bin2hex(random_bytes(32));

// 在表单中包含隐藏字段
<input type="hidden" name="transfer_token" value="<?php echo $transfer_token; ?>">

// 验证提交的令牌
if (!isset($_POST['transfer_token']) || $_POST['transfer_token'] !== $transfer_token) {
    // 令牌无效,拒绝转账请求
}

By implementing these measures, you can Effectively prevent CSRF attacks and protect your PHP applications.

The above is the detailed content of PHP Framework Security Guide: How to Prevent CSRF Attacks?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn