search
HomeBackend DevelopmentPHP TutorialDetailed explanation of the local switch of yii2 csrf

Detailed explanation of the local switch of yii2 csrf

Jan 03, 2018 pm 02:27 PM
csrfyii2switch

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=&#39;csrf&#39; 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 = [&#39;dologin&#39;]; 
 
  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 => [
&#39;enableCookieValidation&#39; => 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 = [&#39;dologin&#39;];
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!

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
How can you check if a PHP session has already started?How can you check if a PHP session has already started?Apr 30, 2025 am 12:20 AM

In PHP, you can use session_status() or session_id() to check whether the session has started. 1) Use the session_status() function. If PHP_SESSION_ACTIVE is returned, the session has been started. 2) Use the session_id() function, if a non-empty string is returned, the session has been started. Both methods can effectively check the session state, and choosing which method to use depends on the PHP version and personal preferences.

Describe a scenario where using sessions is essential in a web application.Describe a scenario where using sessions is essential in a web application.Apr 30, 2025 am 12:16 AM

Sessionsarevitalinwebapplications,especiallyfore-commerceplatforms.Theymaintainuserdataacrossrequests,crucialforshoppingcarts,authentication,andpersonalization.InFlask,sessionscanbeimplementedusingsimplecodetomanageuserloginsanddatapersistence.

How can you manage concurrent session access in PHP?How can you manage concurrent session access in PHP?Apr 30, 2025 am 12:11 AM

Managing concurrent session access in PHP can be done by the following methods: 1. Use the database to store session data, 2. Use Redis or Memcached, 3. Implement a session locking strategy. These methods help ensure data consistency and improve concurrency performance.

What are the limitations of using PHP sessions?What are the limitations of using PHP sessions?Apr 30, 2025 am 12:04 AM

PHPsessionshaveseverallimitations:1)Storageconstraintscanleadtoperformanceissues;2)Securityvulnerabilitieslikesessionfixationattacksexist;3)Scalabilityischallengingduetoserver-specificstorage;4)Sessionexpirationmanagementcanbeproblematic;5)Datapersis

Explain how load balancing affects session management and how to address it.Explain how load balancing affects session management and how to address it.Apr 29, 2025 am 12:42 AM

Load balancing affects session management, but can be resolved with session replication, session stickiness, and centralized session storage. 1. Session Replication Copy session data between servers. 2. Session stickiness directs user requests to the same server. 3. Centralized session storage uses independent servers such as Redis to store session data to ensure data sharing.

Explain the concept of session locking.Explain the concept of session locking.Apr 29, 2025 am 12:39 AM

Sessionlockingisatechniqueusedtoensureauser'ssessionremainsexclusivetooneuseratatime.Itiscrucialforpreventingdatacorruptionandsecuritybreachesinmulti-userapplications.Sessionlockingisimplementedusingserver-sidelockingmechanisms,suchasReentrantLockinJ

Are there any alternatives to PHP sessions?Are there any alternatives to PHP sessions?Apr 29, 2025 am 12:36 AM

Alternatives to PHP sessions include Cookies, Token-based Authentication, Database-based Sessions, and Redis/Memcached. 1.Cookies manage sessions by storing data on the client, which is simple but low in security. 2.Token-based Authentication uses tokens to verify users, which is highly secure but requires additional logic. 3.Database-basedSessions stores data in the database, which has good scalability but may affect performance. 4. Redis/Memcached uses distributed cache to improve performance and scalability, but requires additional matching

Define the term 'session hijacking' in the context of PHP.Define the term 'session hijacking' in the context of PHP.Apr 29, 2025 am 12:33 AM

Sessionhijacking refers to an attacker impersonating a user by obtaining the user's sessionID. Prevention methods include: 1) encrypting communication using HTTPS; 2) verifying the source of the sessionID; 3) using a secure sessionID generation algorithm; 4) regularly updating the sessionID.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor