csrf的思想:
-------------------------------------------------------------
yii使用:
1. 在表单中加一个隐藏域
<div id="tokenId" type="hidden"><?php $this->useCsrfToken();?></div>
public function useCsrfToken(){ $request=Yii::app()->request; echo CHtml::hiddenField($request->csrfTokenName,$request->getCsrfToken(),array(‘id‘=>false)); }
2. 在后台提供订单后验证
public function validateCsrfToken() { $request=Yii::app()->request; if($request->getIsPostRequest()) { // only validate POST requests $cookies=$request->getCookies(); if($cookies->contains($request->csrfTokenName) && isset($_POST[$request->csrfTokenName])) { $tokenFromCookie=$cookies->itemAt($request->csrfTokenName)->value; $tokenFromPost=$_POST[$request->csrfTokenName]; $valid=$tokenFromCookie===$tokenFromPost; } else $valid=false; if(!$valid){ if (Yii::app()->request->isAjaxRequest) { echo Controller::TOKENERROR; Yii::app()->end(); } else { @header(‘HTTP/1.1 403 Forbidden‘); $_SERVER[‘HTTP_REFERER‘] = isset($_SERVER[‘HTTP_REFERER‘]) ? $_SERVER[‘HTTP_REFERER‘] : ‘NO_HTTP_REFERER‘; YiiLog(‘令牌错误, 非法请求! -‘.json_encode($_POST).‘|‘.$_SERVER[‘REQUEST_URI‘].‘|‘.$_SERVER[‘HTTP_REFERER‘]); Yii::app()->end(); } } } }
其实就是,判断cookie里的值和表单隐藏字段的那个值是不是相同。
时间: 2024-11-04 01:39:50