使用Google_Oauth2Service API进行身份验证

时间:2015-04-17 06:27:58

标签: php google-authentication

我有以下登录代码:

  • JS登录控制器:

    token = window.localStorage.getItem("token");
    Ext.php.Users.login(token, function(n) {
    if (Ext.isString(n)) window.location = n;
    else if (n != null) {
        app.user = user;
        r.add({
            id: 0,
            email: t.email,
            password: t.password,
            roles: user.Roles,
            defaultrole: user.DefaultRole
        });
        e.loadMainView("userHome");
    }
    });
    
  • PHP登录功能:

    public function login($token) {
        $client = new Google_Client();
        $oauth2 = new Google_Oauth2Service($client);
    
        if (!empty($token)) {
            $token = base64_decode($token);
            $client->setAccessToken($token);
    
            if (!$client->isAccessTokenExpired()) {
                $user = $oauth2->userinfo->get();
    
                $email = filter_var($user['email'], FILTER_SANITIZE_EMAIL);
    
                $u = $this->getByEmail($email);
    
                if ($u != null) return $u;
            }
    
            $this->logout($token);
        }
    
        $authUrl = $client->createAuthUrl();
        return $authUrl;
    }
    
  • 在我的google / config.php文件中:

    ...
    'oauth2_redirect_uri' => getLoginCallBackUrl(),
    ...
    
  • 该功能,在同一个文件中:

    function getLoginCallBackUrl() {
        $pageURL = 'http';
        //if ($_SERVER["HTTPS"] == "on") {$pageURL .= "s";}
        $pageURL .= "://";
        if ($_SERVER["SERVER_PORT"] != "80") {
            $pageURL .= $_SERVER["SERVER_NAME"].":".$_SERVER["SERVER_PORT"].$_SERVER["REQUEST_URI"];
        } else {
            $pageURL .= $_SERVER["SERVER_NAME"].$_SERVER["REQUEST_URI"];
        }
    
        return substr($pageURL,0,strpos($pageURL,'/api/') + 5) .'login_callback.php';
    }
    

基本上,在我尝试登录后,我被要求进行Google身份验证。我将它传递给测试用户,然后我被重定向回我的Web应用程序:但是,尽管最初加载了令牌,但在应用程序完全加载时丢弃了令牌,我无法登录。尝试再次登录只是重做google身份验证而没有成功

我做错了什么?

编辑:我开始工作了。上面的代码是正确的。模式更改后,我的某个字段出现了拼写错误。我将把问题留给细节,希望代码可以帮助某人,某处。

1 个答案:

答案 0 :(得分:0)

正如我在编辑中所写,上面的代码实际上是正确的(虽然这里没有显示一些控制器登录JS代码)。架构更改后,问题是字段错误。