详解thinkphp6后台添加google登录验证

 5236

thinkphp6后台添加google登录验证

基础环境

系统环境:Windows10 x64

PHP集成环境:phpstudy

PHP依赖管理工具:Composer

手册:Thinkphp6


(一)下载 GoogleAuthenticator 类

(1)代码亲测有效

(2)代码是在tp6环境下,生成的路径可根据当前Tp版本自行修改

  1. /**
  2.  * PHP Class for handling Google Authenticator 2-factor authentication.
  3.  *
  4.  * @author Michael Kliewe
  5.  * @copyright 2012 Michael Kliewe
  6.  * @license http://www.opensource.org/licenses/bsd-license.php BSD License
  7.  *
  8.  * @link http://www.phpgangsta.de/
  9.  */
  10. class GoogleAuthenticator{
  11.     protected $_codeLength = 6;
  12.  
  13.     /**
  14.      * Create new secret.
  15.      * 16 characters, randomly chosen from the allowed base32 characters.
  16.      *
  17.      * @param int $secretLength
  18.      *
  19.      * @return string
  20.      */
  21.     public function createSecret($secretLength = 16)
  22.     {
  23.         $validChars = $this->_getBase32LookupTable();
  24.  
  25.         // Valid secret lengths are 80 to 640 bits
  26.         if ($secretLength < 16 || $secretLength > 128) {
  27.             throw new Exception('Bad secret length');
  28.         }
  29.         $secret = '';
  30.         $rnd = false;
  31.         if (function_exists('random_bytes')) {
  32.             $rnd = random_bytes($secretLength);
  33.         } elseif (function_exists('mcrypt_create_iv')) {
  34.             $rnd = mcrypt_create_iv($secretLength, MCRYPT_DEV_URANDOM);
  35.         } elseif (function_exists('openssl_random_pseudo_bytes')) {
  36.             $rnd = openssl_random_pseudo_bytes($secretLength, $cryptoStrong);
  37.             if (!$cryptoStrong) {
  38.                 $rnd = false;
  39.             }
  40.         }
  41.         if ($rnd !== false) {
  42.             for ($i = 0; $i < $secretLength; ++$i) {
  43.                 $secret .= $validChars[ord($rnd[$i]) & 31];
  44.             }
  45.         } else {
  46.             throw new Exception('No source of secure random');
  47.         }
  48.  
  49.         return $secret;
  50.     }
  51.  
  52.     /**
  53.      * Calculate the code, with given secret and point in time.
  54.      *
  55.      * @param string   $secret
  56.      * @param int|null $timeSlice
  57.      *
  58.      * @return string
  59.      */
  60.     public function getCode($secret, $timeSlice = null)
  61.     {
  62.         if ($timeSlice === null) {
  63.             $timeSlice = floor(time() / 30);
  64.         }
  65.  
  66.         $secretkey = $this->_base32Decode($secret);
  67.  
  68.         // Pack time into binary string
  69.         $time = chr(0).chr(0).chr(0).chr(0).pack('N*', $timeSlice);
  70.         // Hash it with users secret key
  71.         $hm = hash_hmac('SHA1', $time, $secretkey, true);
  72.         // Use last nipple of result as index/offset
  73.         $offset = ord(substr($hm, -1)) & 0x0F;
  74.         // grab 4 bytes of the result
  75.         $hashpart = substr($hm, $offset, 4);
  76.  
  77.         // Unpak binary value
  78.         $value = unpack('N', $hashpart);
  79.         $value = $value[1];
  80.         // Only 32 bits
  81.         $value = $value & 0x7FFFFFFF;
  82.  
  83.         $modulo = pow(10, $this->_codeLength);
  84.  
  85.         return str_pad($value % $modulo, $this->_codeLength, '0', STR_PAD_LEFT);
  86.     }
  87.  
  88.     /**
  89.      * Get QR-Code URL for image, from google charts.
  90.      *
  91.      * @param string $name
  92.      * @param string $secret
  93.      * @param string $title
  94.      * @param array  $params
  95.      *
  96.      * @return string
  97.      */
  98.     public function getQRCodeGoogleUrl($name, $secret, $title = null, $params = array())
  99.     {
  100.         $width = !empty($params['width']) && (int) $params['width'] > 0 ? (int) $params['width'] : 200;
  101.         $height = !empty($params['height']) && (int) $params['height'] > 0 ? (int) $params['height'] : 200;
  102.         $level = !empty($params['level']) && array_search($params['level'], array('L', 'M', 'Q', 'H')) !== false ? $params['level'] : 'M';
  103.  
  104.         $urlencoded = urlencode('otpauth://totp/'.$name.'?secret='.$secret.'');
  105.         if (isset($title)) {
  106.             $urlencoded .= urlencode('&issuer='.urlencode($title));
  107.         }
  108.  
  109.         return "https://api.qrserver.com/v1/create-qr-code/?data=$urlencoded&size=${width}x${height}&ecc=$level";
  110.     }
  111.  
  112.     /**
  113.      * Check if the code is correct. This will accept codes starting from $discrepancy*30sec ago to $discrepancy*30sec from now.
  114.      *
  115.      * @param string   $secret
  116.      * @param string   $code
  117.      * @param int      $discrepancy      This is the allowed time drift in 30 second units (8 means 4 minutes before or after)
  118.      * @param int|null $currentTimeSlice time slice if we want use other that time()
  119.      *
  120.      * @return bool
  121.      */
  122.     public function verifyCode($secret, $code, $discrepancy = 1, $currentTimeSlice = null)
  123.     {
  124.         if ($currentTimeSlice === null) {
  125.             $currentTimeSlice = floor(time() / 30);
  126.         }
  127.  
  128.         if (strlen($code) != 6) {
  129.             return false;
  130.         }
  131.  
  132.         for ($i = -$discrepancy; $i <= $discrepancy; ++$i) {
  133.             $calculatedCode = $this->getCode($secret, $currentTimeSlice + $i);
  134.             if ($this->timingSafeEquals($calculatedCode, $code)) {
  135.                 return true;
  136.             }
  137.         }
  138.  
  139.         return false;
  140.     }
  141.  
  142.     /**
  143.      * Set the code length, should be >=6.
  144.      *
  145.      * @param int $length
  146.      *
  147.      * @return PHPGangsta_GoogleAuthenticator
  148.      */
  149.     public function setCodeLength($length)
  150.     {
  151.         $this->_codeLength = $length;
  152.  
  153.         return $this;
  154.     }
  155.  
  156.     /**
  157.      * Helper class to decode base32.
  158.      *
  159.      * @param $secret
  160.      *
  161.      * @return bool|string
  162.      */
  163.     protected function _base32Decode($secret)
  164.     {
  165.         if (empty($secret)) {
  166.             return '';
  167.         }
  168.  
  169.         $base32chars = $this->_getBase32LookupTable();
  170.         $base32charsFlipped = array_flip($base32chars);
  171.  
  172.         $paddingCharCount = substr_count($secret, $base32chars[32]);
  173.         $allowedValues = array(6, 4, 3, 1, 0);
  174.         if (!in_array($paddingCharCount, $allowedValues)) {
  175.             return false;
  176.         }
  177.         for ($i = 0; $i < 4; ++$i) {
  178.             if ($paddingCharCount == $allowedValues[$i] &&
  179.                 substr($secret, -($allowedValues[$i])) != str_repeat($base32chars[32], $allowedValues[$i])) {
  180.                 return false;
  181.             }
  182.         }
  183.         $secret = str_replace('=', '', $secret);
  184.         $secret = str_split($secret);
  185.         $binaryString = '';
  186.         for ($i = 0; $i < count($secret); $i = $i + 8) {
  187.             $x = '';
  188.             if (!in_array($secret[$i], $base32chars)) {
  189.                 return false;
  190.             }
  191.             for ($j = 0; $j < 8; ++$j) {
  192.                 $x .= str_pad(base_convert(@$base32charsFlipped[@$secret[$i + $j]], 10, 2), 5, '0', STR_PAD_LEFT);
  193.             }
  194.             $eightBits = str_split($x, 8);
  195.             for ($z = 0; $z < count($eightBits); ++$z) {
  196.                 $binaryString .= (($y = chr(base_convert($eightBits[$z], 2, 10))) || ord($y) == 48) ? $y : '';
  197.             }
  198.         }
  199.  
  200.         return $binaryString;
  201.     }
  202.  
  203.     /**
  204.      * Get array with all 32 characters for decoding from/encoding to base32.
  205.      *
  206.      * @return array
  207.      */
  208.     protected function _getBase32LookupTable()
  209.     {
  210.         return array(
  211.             'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', //  7
  212.             'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', // 15
  213.             'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', // 23
  214.             'Y', 'Z', '2', '3', '4', '5', '6', '7', // 31
  215.             '=',  // padding char
  216.         );
  217.     }
  218.  
  219.     /**
  220.      * A timing safe equals comparison
  221.      * more info here: http://blog.ircmaxell.com/2014/11/its-all-about-time.html.
  222.      *
  223.      * @param string $safeString The internal (safe) value to be checked
  224.      * @param string $userString The user submitted (unsafe) value
  225.      *
  226.      * @return bool True if the two strings are identical
  227.      */
  228.     private function timingSafeEquals($safeString, $userString)
  229.     {
  230.         if (function_exists('hash_equals')) {
  231.             return hash_equals($safeString, $userString);
  232.         }
  233.         $safeLen = strlen($safeString);
  234.         $userLen = strlen($userString);
  235.  
  236.         if ($userLen != $safeLen) {
  237.             return false;
  238.         }
  239.  
  240.         $result = 0;
  241.  
  242.         for ($i = 0; $i < $userLen; ++$i) {
  243.             $result |= (ord($safeString[$i]) ^ ord($userString[$i]));
  244.         }
  245.  
  246.         // They are only identical strings if $result is exactly 0...
  247.         return $result === 0;
  248.     }
  249. }


(二)使用

(1)生成 谷歌秘钥和验证二维码

(2)将谷歌秘钥和验证二维码保存到数据库

  1. //谷歌验证码
  2. $google=new GoogleAuthenticator();
  3. //生成验证秘钥
  4. $secret=$google->createSecret();
  5. //生成验证二维码 $username 需要绑定的用户名
  6. $qrCodeUrl = $google->getQRCodeGoogleUrl($username, $secret);
  7. //存入数据库
  8. .....省略代码

(3)谷歌验证

  1. $google=new GoogleAuthenticator();
  2. //$google_secret 存入的谷歌秘钥  ,$code 谷歌动态验证码
  3. $checkResult = $google->verifyCode($google_secret, $code, 4);
  4. if (!$checkResult){
  5.     $this->error('谷歌验证码错误');
  6. }


本文网址:https://www.zztuku.com/detail-8980.html
站长图库 - 详解thinkphp6后台添加google登录验证
申明:如有侵犯,请 联系我们 删除。

评论(0)条

您还没有登录,请 登录 后发表评论!

提示:请勿发布广告垃圾评论,否则封号处理!!

    编辑推荐