/** * 获取用于权限验证的 token * * @param string $username 用户名 * @param string $password 密码 * @param string $grant_type 验证类型 * @return array */ public function get_token($username, $password, $grant_type) : array { if ($grant_type !== 'client_credentials') { return ['error' => 'unsupported_grant_type', 'error_description' => '不支持该种验证类型']; } if (!$username || !$password) { return ['error' => 'invalid_request', 'error_description' => '用户名和密码不能为空']; } $m_au = new ApiUser(); $api_user = $m_au->find(['username' => $username, 'password' => $password], 'uid, allowed_ip'); if (!$api_user) { return ['error' => 'invalid_client', 'error_description' => '用户名或密码错误']; } $ip = $_SERVER['REMOTE_ADDR']; if ($api_user['allowed_ip'] && strpos($api_user['allowed_ip'], $ip) === false) { return ['error' => 'unauthorized_client', 'error_description' => '您的IP无权限访问接口']; } // 生成 token $dateline = time(); $uid = $api_user['uid']; $m_al = new ApiLogin(); $api_login = $m_al->find(['uid' => $uid, 'dateline >=' => $dateline - self::CACHE_TIME], 'token, dateline'); if ($api_login) { // 从库里取出 token $token = $api_login['token']; $dateline = $api_login['dateline']; } else { // 生成 token,并入库 $token = hash_hmac('md5', $uid . $dateline, self::TOKEN_KEY); $m_al->add(['uid' => $uid, 'token' => $token, 'dateline' => $dateline]); } mem_set('api_' . $token, $uid, self::CACHE_TIME); // 存入 memcache return ['access_token' => $token, 'token_type' => 'Bearer', 'expires_in' => self::CACHE_TIME, 'expires_at' => $dateline + self::CACHE_TIME]; }