How do I prevent cross-site request forgery (CSRF) attacks in Yii?
Jul 15, 2025 am 12:41 AMYii The key to preventing CSRF attacks is to use the built-in mechanism correctly. First, Yii enables CSRF protection by default and generates tokens automatically. The token will be automatically added when using ActiveForm or Html::beginForm; second, when writing forms manually or using AJAX, you need to obtain the token through Yii::$app->request->csrfToken, and it is recommended to pass it to JS through meta tags; third, for the API interface, you can choose to turn off CSRF and strengthen other authentications such as JWT, or pass tokens through header; finally, sensitive operations should be avoided in GET requests, and only use POST/PUT/DELETE to perform state changes.
Preventing cross-site request forgery (CSRF) attacks is not actually complicated in Yii, but it is very critical. The Yii framework itself has built-in CSRF protection mechanism, which is enabled by default. As long as you understand how it works and make reasonable configurations based on actual needs, you can effectively prevent such attacks.
Turn on and correctly use Yii's CSRF protection
Yii generates a unique CSRF token for each session by default and validates it in each POST request. If you are using form assistance methods provided by Yii such as ActiveForm or Html::beginForm, the token will be automatically added to the form without manual processing.
But if you write the form yourself or submit data with AJAX, you need to manually insert the CSRF token. For example:
- Get token in view:
Yii::$app->request->csrfToken
- When using it in JavaScript, it is recommended to put the token in the meta tag and then get it through JS:
<meta name="csrf-token" content="<?= Yii::$app->request->csrfToken ?>">
This can avoid XSS risks and facilitate front-end calls.
Pay special attention to CSRF settings for API interfaces
For front-end and back-end separate applications or RESTful API interfaces, cookie/session-based authentication is usually not recommended. At this time, CSRF protection may need to be turned off or handled in another way.
You can disable CSRF verification in the controller or module configuration:
public function init() { $this->enableCsrfValidation = false; parent::init(); }
However, it should be noted that other security measures should be strengthened while closing CSRF, such as using OAuth, JWT authentication, etc. to ensure the legitimacy of the request source.
Also, if you still want to keep CSRF verification, you can pass the token through the header instead of putting it in the form. The front-end brings X-CSRF-Token
in the request header, and the back-end can recognize it.
Note that GET requests should not perform sensitive operations
Many CSRF attacks take advantage of the user's browser's automatic cookies, and GET requests are most likely to be triggered. Therefore, never let GET requests perform any sensitive operations , such as deleting data, modifying user information, etc.
Even if you enable CSRF protection, you should follow this principle. Because by default Yii does not perform CSRF verification on GET requests, because it assumes that GET is "read-only".
So the correct way is:
- Use POST/PUT/DELETE to perform state changes
- If GET is required, do not involve user identity changes or sensitive data operations
Let's summarize
Basically that's it. Yii's CSRF protection mechanism is already very complete. As long as you pay attention to a few key points during the development process - correctly using tokens, reasonably configuring the API interface, and avoiding dangerous operations in GET, you can be well protected against CSRF attacks. These seem simple, but if you don't pay attention, it is easy to ignore a certain link, resulting in security vulnerabilities.
The above is the detailed content of How do I prevent cross-site request forgery (CSRF) attacks in Yii?. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Cross-site scripting (XSS) and cross-site request forgery (CSRF) protection in Laravel With the development of the Internet, network security issues have become more and more serious. Among them, Cross-SiteScripting (XSS) and Cross-SiteRequestForgery (CSRF) are one of the most common attack methods. Laravel, as a popular PHP development framework, provides users with a variety of security mechanisms

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, store it in the session or cookie. Include a hidden field in your application for submitting that token

Comparative analysis of PHPSession cross-domain and cross-site request forgery With the development of the Internet, the security of web applications has become particularly important. PHPSession is a commonly used authentication and session tracking mechanism when developing web applications, while cross-domain requests and cross-site request forgery (CSRF) are two major security threats. In order to protect the security of user data and applications, developers need to understand the difference between Session cross-domain and CSRF, and adopt

The Yii framework is an open source PHP Web application framework that provides numerous tools and components to simplify the process of Web application development, of which data query is one of the important components. In the Yii framework, we can use SQL-like syntax to access the database to query and manipulate data efficiently. The query builder of the Yii framework mainly includes the following types: ActiveRecord query, QueryBuilder query, command query and original SQL query

With the continuous development of cloud computing technology, data backup has become something that every enterprise must do. In this context, it is particularly important to develop a highly available cloud backup system. The PHP framework Yii is a powerful framework that can help developers quickly build high-performance web applications. The following will introduce how to use the Yii framework to develop a highly available cloud backup system. Designing the database model In the Yii framework, the database model is a very important part. Because the data backup system requires a lot of tables and relationships

The main differences between Laravel and Yii are design concepts, functional characteristics and usage scenarios. 1.Laravel focuses on the simplicity and pleasure of development, and provides rich functions such as EloquentORM and Artisan tools, suitable for rapid development and beginners. 2.Yii emphasizes performance and efficiency, is suitable for high-load applications, and provides efficient ActiveRecord and cache systems, but has a steep learning curve.

The steps to containerize and deploy Yii applications using Docker include: 1. Create a Dockerfile and define the image building process; 2. Use DockerCompose to launch Yii applications and MySQL database; 3. Optimize image size and performance. This involves not only specific technical operations, but also understanding the working principles and best practices of Dockerfile to ensure efficient and reliable deployment.

In PHP, you can effectively prevent CSRF attacks by using unpredictable tokens. Specific methods include: 1. Generate and embed CSRF tokens in the form; 2. Verify the validity of the token when processing the request.
