Detailed explanation of the local switch of yii2 csrf
This article mainly introduces the example code for partially closing (opening) CSRF verification in yii2. The editor thinks it’s pretty good, so I’d like to share it with you now and give it as a reference. I hope to be helpful.
(1) For global use, we directly set enableCookieValidation to true in the configuration file
request => [ 'enableCookieValidation' => true, ]
If you do not need to use csrf, set 'enableCookieValidation' => false , but this is unsafe, so enableCookieValidation in yii\web\request of yii2 is set to true by default, which means csrf is enabled by default, so we can also not configure this value and enable it by default.
If you enable csrf, because it is global, authentication will be required for any post request, so when we post data, we must set the csrf data to be hidden in the form.
<input type="hidden" name="_csrf" id='csrf' value="<?= Yii::$app->request->csrfToken ?>">
When posting data, you must post this value. The value generated is = Yii::$app->request->csrfToken ?>, and an encrypted csrfToken is returned. .
So whether it is a post form or an ajax post, the value of csrfToken must be set, and it must be posted when submitting. If not, an error will occur and authentication will not pass.
(2) If you don’t want to use csrf verification in some controllers, what should you do?
The method is very simple, set it directly
public $enableCsrfValidation = false ,
Because this Controller inherits from yii\web\Controller, it will be equivalent to inheriting from the enableCsrfValidation attribute, then create the controller When the instance is used, the CSRF function will be turned off in this controller, and verification will not be performed when accessing the post of this controller.
For example, when we develop the API, when the WeChat interface needs to post data to our interface, since the WeChat side does not know the csrfToken, when accessing the post data, if it is turned on If it is a global csrf, it will definitely not be accessible successfully. So at this time, you need to turn off the csrf of this API.
3) What if you want to specifically close a certain action?
Sometimes in some functions, we need to turn off csrf verification in a certain action. We know that the verification of csrf is implemented in beforeAction($Action). Next, we can rewrite the beforeAction($action) method in the Controller.
public function beforeAction($action) { $currentaction = $action->id; $novalidactions = ['dologin']; if(in_array($currentaction,$novalidactions)) { $action->controller->enableCsrfValidation = false; } parent::beforeAction($action); return true; }
The parameter $action passed in is the controller for this access. The instantiated object contains a lot of information, which you can print and see.
First execute $action->id to obtain the current accessed action name. And $novalidactions is an array, which contains the action names. These actions are all operations that you need to turn off CSRF authentication (operations that need to turn off CSRF authentication).
Whether the action currently accessed is in this $novalidactions. If it is, it means that this action needs to turn off the csrf function, so set the controller instance to
$action->controller->enableCsrfValidation = false
Next, parent::beforeAction($action) is executed. At this time, the enableCsrfValidation of the controller instance in the passed in $action has changed to false.
In the end, true must be returned, otherwise, the action operation will not be executed.
(4) What if it is partially turned on?
First set
request => [ 'enableCookieValidation' => false, ]
in the configuration file to not use csrf globally.
(a) To enable it in the controller, you only need to set
public $enableCsrfValidation = true
and the entire controller will be enabled
(b) To enable it in the action
public function beforeAction($action) { $currentaction = $action->id; $accessactions = ['dologin']; i f(in_array($currentaction,$accessactions)) { $action->controller->enableCsrfValidation = true; } parent::beforeAction($action); return true; }
$accessactions is the name of the action that needs to enable csrf. Set $action->controller->enableCsrfValidation = true, and the current operation can enable csrf.
Related recommendations:
Detailed explanation of how the Yii framework implements logging to custom files
Detailed explanation of Yii framework's simple extension class for batch insertion of data
##Detailed explanation of restful api authorization verification of yii2
The above is the detailed content of Detailed explanation of the local switch of yii2 csrf. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

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

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

Undress AI Tool
Undress images for free

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

When using the win10 system to connect to Bluetooth, I suddenly found that the Bluetooth connection option was missing, could not be found anywhere, or the Bluetooth function could not be used. What should I do if the Bluetooth switch is missing in Windows 10? For users who are troubled by this problem, let’s take a look at the detailed recovery tutorial for missing Bluetooth switch in win10 system~. The tutorial for retrieving the Bluetooth switch in win10 system is missing: 1. Update the Bluetooth driver and restart after installation. If you still can’t find the Bluetooth switch option. 2. First press Win+R on the keyboard, open the operation window, enter services.msc and open it. 3. After entering the service interface, we search downwards and find the Bluetooth support service. 4. Double-click to open [Bluetooth Support Service], stop the service state, and click [Start]. 5.Starting

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

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

How to remove jquery from yii2: 1. Edit the AppAsset.php file and comment out the "yii\web\YiiAsset" value in the variable $depends; 2. Edit the main.php file and add the configuration "'yii" under the field "components" \web\JqueryAsset' => ['js' => [],'sourcePath' => null,]," to remove the jquery script.

PhoneLink in Windows 11 is getting another useful feature. After getting iPhone integration not too long ago, Microsoft is reportedly working on bringing a switch that will make it easier to control your phone from your PC. Or, at least so far. The Redmond-based tech giant rolled out a build for Windows Insiders in the Dev channel. It's called Build23590, and while it brings the sad news that StepsRecorder is deprecated here, there's an interesting hidden switch in the Settings app. The new toggle reads "Allow this computer to access your mobile device." Still incomplete, but that's a sign of a good thing

With the continuous development of the Internet, there are more and more web applications. However, security issues are also attracting more and more attention. CSRF (CrossSiteRequestForgery, cross-site request forgery) attack is a common network security problem. What is a CSRF attack? The so-called CSRF attack means that the attacker steals the user's identity and performs illegal operations in the user's name. In layman's terms, it means that the attacker uses the user's login status to perform some illegal operations without the user's knowledge.

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.
