Oauth 2 $ client-> getAccessToken()返回空值 [英] Oauth 2 $client->getAccessToken() Returns Null value

查看:181
本文介绍了Oauth 2 $ client-> getAccessToken()返回空值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要你的帮助。我使用codeigniter MVC框架使用google客户端库登录到我的网站。每一件事情都很好,希望$ client-> getAccessToken()当谷歌重定向与代码,我做下面的代码。 $ client-> getAccessToken()返回空值。我看到很多教程,但没有得到任何帮助。这里是我的控制器功能之一的代码。


$ b $ pre $ public function login()
{
/ /在控制器
include_once APPPATH中包含来自google-php-client库的两个文件。 THIRD_PARTY /谷歌-API的PHP的客户端/供应商/ autoload.php;

//在Google Developer Console中创建的项目中存储变量值
$ client_id ='XXXXXX';
$ client_secret ='XXXXX';
$ redirect_uri ='path / to / mysite / login / loginGoogle';
$ simple_api_key ='XXXXXXX';

//创建客户端访问Google API的请求
$ client = new Google_Client();
$ client-> setApplicationName(mysite);
$ client-> setClientId($ client_id);
$ client-> setClientSecret($ client_secret);
$ client-> setRedirectUri($ redirect_uri);
$ client-> setDeveloperKey($ simple_api_key);
$ client-> addScope(https://www.googleapis.com/auth/userinfo.email);

$ authUrl = $ client-> createAuthUrl();
$ data ['authUrl'] = $ authUrl;

$ this-> load-> view('login',$ data);
}

之后,当谷歌验证并重定向到我的重定向uri这是另一个控制器功能如下。问题出在这个函数中。

  public function loginGoogle()
{
//包含两个文件来自控制器
中的google-php-client库include_once APPPATH。 'third_party / google-api-php-client / vendor /autoload.php';
$ client_id ='XXXXXX';
$ client_secret ='XXXXX';
$ redirect_uri ='path / to / mysite / login / loginGoogle';
$ simple_api_key ='XXXXXXX';

//创建客户端访问Google API的请求
$ client = new Google_Client();
$ client-> setApplicationName(mysite);
$ client-> setClientId($ client_id);
$ client-> setClientSecret($ client_secret);
$ client-> setRedirectUri($ redirect_uri);
$ client-> setDeveloperKey($ simple_api_key);
$ client-> addScope(https://www.googleapis.com/auth/userinfo.email);
$ objOAuthService = new Google_Service_Oauth2($ client);

//将访问令牌添加到会话
if(isset($ _get [($ _ SESSION ['access_token'])){

if代码'])){
$ client-> authenticate($ _ GET ['code']);
$ token = $ client-> getAccessToken();
$ _SESSION ['access_token'] = $ token;
print_r($ this - > session - > userdata()); exit;
header('Location:'。filter_var($ redirect_uri,FILTER_SANITIZE_URL)); ($ _ SESSION ['access_token'])&&& $ _SESSION ['access_token'])设置访问令牌以发出请求



{
$ client-> setAccessToken($ _ SESSION ['access_token']);

//从Google获取用户数据并将它们存储在$ data
中(if($ client-> getAccessToken()){
$ userData = $ objOAuthService-> userinfo->得到();
$ data ['userData'] = $ userData;
$ _SESSION ['access_token'] = $ client-> getAccessToken();
}}

这里第二个函数getAccessToken不会返回任何结果,而且google会抛出异常。请帮助我。

解决方案

它看起来像你永远不会得到刷新令牌。有两种不同的令牌,访问令牌每隔几个小时左右过期,但刷新令牌只在重定向要求用户许可时才发送一次。它需要存储在安全的地方,并在将来用于刷新访问令牌。
这里是我的codeigniter代码看起来像访问Google API的代码(这会替换loginGoogle函数中的if语句:

 <$ c $ ($ client-> isAccessTokenExpired()){
$ client->}如果($ refresh_token_accessed_from_my_database){
//如果session不包含有效的Access令牌,则获得一个新的
。 ; refreshToken($ refresh_token_accessed_from_my_database);
}
//我们现在有访问令牌,启动服务
$ this-> service = new Google_Service_Calendar($ client);
}
else {
//用户从来没有被授权过,所以我们要求ok
if(isset($ _ GET ['code'])){
//创建刷新和访问令牌
$ credentials = $ client-> authenticate($ _ GET ['code']);

//存储刷新标记供进一步使用
// I stor在我的数据库中,我见过其他人将它存储在服务器上安全位置的文件中
$ refresh_token = $ credentials ['refresh_token'];
// refresh_token-> persist_somewhere()

//将访问令牌存储在会话中,以便我们可以在
之后获得它//回调重定向
$ _SESSION ['access_token'] = $ client-> getAccessToken();
$ redirect_uri ='http://'。 $ _SERVER ['HTTP_HOST']。 $ _SERVER [ PHP_SELF];
header('Location:'。filter_var($ redirect_uri,FILTER_SANITIZE_URL));

$ b $ if(!isset($ _ SESSION ['access_token'])){
$ auth_url = $ client-> createAuthUrl();
header('Location:'。filter_var($ auth_url,FILTER_SANITIZE_URL));

$ b $ if(isset($ _ SESSION ['access_token'])&& $ _SESSION ['access_token']){
$ client-> setAccessToken($ _SESSION [ 'ACCESS_TOKEN']);
$ this-> service = new Google_Service_Calendar($ client);
}


I need your help.i am using codeigniter MVC framework for signing in to my site using google client library. every thing is working fine expect $client->getAccessToken() when google redirects with code and i do the following code. $client->getAccessToken() return null value. and i saw many tutorials but didn't get any help. here is my code for controller function one. In this function i set my credentials to create authUrl.

public function login()
{
    // Include two files from google-php-client library in controller
    include_once APPPATH . 'third_party/google-api-php-client/vendor/autoload.php';

    // Store values in variables from project created in Google Developer Console
    $client_id = 'XXXXXX';
    $client_secret = 'XXXXX';
    $redirect_uri = 'path/to/mysite/login/loginGoogle';
    $simple_api_key = 'XXXXXXX';

    // Create Client Request to access Google API
    $client = new Google_Client();
    $client->setApplicationName("mysite");
    $client->setClientId($client_id);
    $client->setClientSecret($client_secret);
    $client->setRedirectUri($redirect_uri);
    $client->setDeveloperKey($simple_api_key);
    $client->addScope("https://www.googleapis.com/auth/userinfo.email");

    $authUrl = $client->createAuthUrl();
    $data['authUrl'] = $authUrl;

    $this->load->view('login',$data);
}

And after that when google authenticate and redirects to my redirect uri which is an other controller function which is given below. and problem is in this function.

public function loginGoogle()
{
    // Include two files from google-php-client library in controller
    include_once APPPATH . 'third_party/google-api-php-client/vendor /autoload.php';
       $client_id = 'XXXXXX';
        $client_secret = 'XXXXX';
        $redirect_uri = 'path/to/mysite/login/loginGoogle';
        $simple_api_key = 'XXXXXXX';

    // Create Client Request to access Google API
    $client = new Google_Client();
    $client->setApplicationName("mysite");
    $client->setClientId($client_id);
    $client->setClientSecret($client_secret);
    $client->setRedirectUri($redirect_uri);
    $client->setDeveloperKey($simple_api_key);
    $client->addScope("https://www.googleapis.com/auth/userinfo.email");
$objOAuthService = new Google_Service_Oauth2($client);

    // Add Access Token to Session
    if(!isset($_SESSION['access_token'])){

        if (isset($_GET['code'])) {
            $client->authenticate($_GET['code']);
            $token = $client->getAccessToken();                 
            $_SESSION['access_token'] = $token;
            print_r($this -> session -> userdata());exit;
            header('Location: ' . filter_var($redirect_uri, FILTER_SANITIZE_URL));
        }
    }
    // Set Access Token to make Request
    if (isset($_SESSION['access_token']) && $_SESSION['access_token']) {
        $client->setAccessToken($_SESSION['access_token']);
    }
    // Get User Data from Google and store them in $data
    if ($client->getAccessToken()) {
        $userData = $objOAuthService->userinfo->get();
        $data['userData'] = $userData;
        $_SESSION['access_token'] = $client->getAccessToken();
    }}

here in second function getAccessToken return nothing and google throws expection. Please help me out.

解决方案

It looks like you never get the refresh token. There are two different tokens, the access token expires every few hours or so, but the refresh token is only sent the one time when the redirect asks the user for permission. It needs to be stored somewhere secure and is used in the future to refresh the access token. Here's what my codeigniter code looks like to access the Google API (this would replace your if statements in the loginGoogle function:

        if($refresh_token_accessed_from_my_database) {
            //If session contains no valid Access token, get a new one
            if ($client->isAccessTokenExpired()) {
                $client->refreshToken($refresh_token_accessed_from_my_database);
            }
            //We have access token now, launch the service
            $this->service = new Google_Service_Calendar($client);
        }
        else {
            //User has never been authorized, so let's ask for the ok
            if (isset($_GET['code'])) {
                //Creates refresh and access tokens
                $credentials = $client->authenticate($_GET['code']);

                //Store refresh token for further use
                //I store mine in the DB, I've seen others store it in a file in a secure place on the server
                $refresh_token = $credentials['refresh_token'];
                //refresh_token->persist_somewhere()

                //Store the access token in the session so we can get it after
                //the callback redirect
                $_SESSION['access_token'] = $client->getAccessToken();
                $redirect_uri = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'];
                header('Location: ' . filter_var($redirect_uri, FILTER_SANITIZE_URL));
            }

            if (!isset($_SESSION['access_token'])) {
                $auth_url = $client->createAuthUrl();
                header('Location: ' . filter_var($auth_url, FILTER_SANITIZE_URL));
            }

            if (isset($_SESSION['access_token']) && $_SESSION['access_token']) {
                $client->setAccessToken($_SESSION['access_token']);
                $this->service = new Google_Service_Calendar($client);
            }

这篇关于Oauth 2 $ client-&gt; getAccessToken()返回空值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆