Google oauth2 access token expires in 1 hour. I want to make it 1 day

纵饮孤独 提交于 2020-01-02 07:51:12

问题


I have created a project with Google OAuth2 credentials for use with Google calendar.

However the access toke expires in every 1 hour.

Can someone please help me change the expire time to 1 day.

I have use this code to access the google calendar events:

$client = new Google_Client();
$client->setApplicationName("Client_Library_Examples");
$client->setClientId($client_id);
$client->setClientSecret($client_secret);
$client->setRedirectUri($redirect_uri);
$client->setAccessType('offline');
$client->setScopes(array('https://www.googleapis.com/auth/calendar'));

if (isset($_GET['code']))
    $google_oauth_code = $_GET['code'];
    $client->authenticate($_GET['code']);  
    $_SESSION['token'] = $client->getAccessToken();
    $_SESSION['last_action'] = time();
}

回答1:


There are some things you need to understand about Oauth2. Access tokens are short lived they only last for one hour this is the way they work and you can not change that.

What you should be doing is storing the refresh token returned by the authentication process when you set the following.

$client->setAccessType('offline');

By using the refresh token you can request a new access token. This example might help it appears to show how to set the access token when it has expired. upload example

probably something along this lines.

    $client = new Google_Client();
    $client->setApplicationName(APPNAME);       
    $client->setClientId(CLIENTID);             // client id
    $client->setClientSecret(CLIENTSECRET);     // client secret 
    $client->setRedirectUri(REDIRECT_URI);      // redirect uri
    $client->setApprovalPrompt('auto');

    $client->setAccessType('offline');         // generates refresh token

    $token = $_COOKIE['ACCESSTOKEN'];          

    // if token is present in cookie
    if($token){
        // use the same token
        $client->setAccessToken($token);
    }

    // this line gets the new token if the cookie token was not present
    // otherwise, the same cookie token
    $token = $client->getAccessToken();

    if($client->isAccessTokenExpired()){  // if token expired
        $refreshToken = json_decode($token)->refresh_token;

        // refresh the token
        $client->refreshToken($refreshToken);
    }

    return $client;
}


来源:https://stackoverflow.com/questions/42996918/google-oauth2-access-token-expires-in-1-hour-i-want-to-make-it-1-day

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!