ThinkPHP token authentication instance

  • 2021-07-01 06:56:55
  • OfStack

ThinkPHP has built-in form token verification function, which can effectively prevent remote submission of forms and other security protection.
The configuration parameters related to form token authentication are:


'TOKEN_ON'=>true, //  Turn on token authentication  
'TOKEN_NAME'=>'__hash__', //  Form hidden field name for token validation  
'TOKEN_TYPE'=>'md5', // Token hash validation rule   Default to MD5 

If the form token verification function is turned on, the system will automatically generate a hidden field with the name TOKEN_NAME in the template file with the form, and its value is a hash string generated by TOKEN_TYPE, which is used to realize the automatic token verification of the form.

The automatically generated hidden field is located before the end flag of the form Form. If you want to control the position of the hidden field, you can manually add the __TOKEN__ flag on the form page, and the system will automatically replace it when outputting the template. If you can add __NOTOKEN__ to the form page without requiring token validation for individual forms with form token validation turned on, the system ignores token validation for the current form.

If more than one form exists on the page, it is recommended to add the __TOKEN__ identity and ensure that only one form requires token validation.

The model class will automatically validate the form token when creating the data object. If you do not use the create method to create the data object, you need to manually call the autoCheckToken method of the model for form token validation. If false is returned, the form token validation error is indicated. For example:


$User = M("User"); //  Instantiation User Object  
//  Manual token verification  
if (!$User->autoCheckToken($_POST)){ 
//  Token validation error  
} 

A common template replacement function is defined in View. class. php of ThinkPHP framework


protected function templateContentReplace($content) {
 //  System default special variable replacement 
 $replace = array(
 '../Public' => APP_PUBLIC_PATH,//  Project public directory 
 '__PUBLIC__' => WEB_PUBLIC_PATH,//  Site public directory 
 '__TMPL__' => APP_TMPL_PATH, //  Project template directory 
 '__ROOT__' => __ROOT__, //  Current Web site address 
 '__APP__' => __APP__, //  Current project address 
 '__UPLOAD__' => __ROOT__.'/Uploads',
 '__ACTION__' => __ACTION__, //  Current operation address 
 '__SELF__' => __SELF__, //  Current page address 
 '__URL__' => __URL__,
 '__INFO__' => __INFO__,
 );
 if(defined('GROUP_NAME'))
 {
 $replace['__GROUP__'] = __GROUP__;//  Current project address 
 }
 if(C('TOKEN_ON')) {
 if(strpos($content,'{__TOKEN__}')) {
 //  Specify the form token hidden field location 
 $replace['{__TOKEN__}'] = $this->buildFormToken();
 }elseif(strpos($content,'{__NOTOKEN__}')){
 //  Mark as not requiring token authentication 
 $replace['{__NOTOKEN__}'] = '';
 }elseif(preg_match('/<\/form(\s*)>/is',$content,$match)) {
 //  Intelligent Generation of Form Token Hidden Fields 
 $replace[$match[0]] = $this->buildFormToken().$match[0];
 }
 }
 //  Allows users to customize string substitution of templates 
 if(is_array(C('TMPL_PARSE_STRING')) )
 $replace = array_merge($replace,C('TMPL_PARSE_STRING'));
 $content = str_replace(array_keys($replace),array_values($replace),$content);
 return $content;
 }

The above if (C ('TOKEN_ON')) judges the open state of token authentication. If it is open, the buildFormToken () method is called, $_ SESSION [$tokenName] = $tokenValue; You're actually assigning a value to $_SESSION ['__hash__']. If you do not want to perform token validation, just click on the page's < /form > Just add {__NOTOKEN__} before, and it will be replaced with null by the function.

The token validation function is defined in the Model. class. php class of ThinkPHP


//  Form token authentication 
 if(C('TOKEN_ON') && !$this->autoCheckToken($data)) {
 $this->error = L('_TOKEN_ERROR_');
 return false;
 }

 //  Automatic form token verification 
 public function autoCheckToken($data) {
 $name = C('TOKEN_NAME');
 if(isset($_SESSION[$name])) {
 //  Token authentication is currently required 
 if(empty($data[$name]) || $_SESSION[$name] != $data[$name]) {
 //  Illegal submission 
 return false;
 }
 //  Verify that destruction is complete session
 unset($_SESSION[$name]);
 }
 return true;
 }

Related articles: