Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Authentication on google: OAuth2 keeps returning 'invalid_grant'

Tags:

I started to configure google calendar on my new application. I almost made an exact copy of the authentication code displayed at google developers ( https://developers.google.com/google-apps/calendar/instantiate ), but i keep getting the following error:

Error fetching OAuth2 access token, message: 'invalid_grant'

I'm currently using Fork-CMS ( http://www.fork-cms.com ), a young lightweigth CMS. I correctly configured the config.php file of the google-api-php-client. (client-id, client-secret, redirect-uri, development key,...) and the redirect uri is correctly set on the google api's console. My code looks as follows:

<?php

/**
* This is a widget with a calendar implementation.
*
* @package       frontend
* @subpackage    events
*
* @author        Michiel Vlaminck <[email protected]>
*/
class FrontendEventsWidgetCalendar extends FrontendBaseWidget
{

    private $events = array();
    private $authUrl = array();

    /**
    * Execute the extra
    *
    * @return    void
    */
    public function execute()
    {      
        // call parent
        parent::execute();

        // load template
        $this->loadTemplate();

        // get data
        $this->getData();

        // parse
        $this->parse();
    }


    /**
    * Get the data from Google Calendar
    * This method is only executed if the template isn't cached
    *
    * @return    void
    */
    private function getData()
    {
        require_once PATH_LIBRARY . '/external/google-api-php-client/src/apiClient.php';
        require_once PATH_LIBRARY . '/external/google-api-php-client/src/contrib/apiCalendarService.php';

        $client = new apiClient();

        $service = new apiCalendarService($client);

        if (isset($_SESSION['oauth_access_token'])) {
            $client->setAccessToken($_SESSION['oauth_access_token']);
        } else {
            $token = $client->authenticate();
            $_SESSION['oauth_access_token'] = $token;
        }

        if ($client->getAccessToken()) {

            $calId = FrontendEventsModel::getCalendarId((int) $this->data['id']);
            $calId = $calId[0]['calendar_id'];

            $events = $service->events->listEvents($calId);
            $this->events = $events['items'];

            $_SESSION['oauth_access_token'] = $client->getAccessToken();

        } else {
            $this->authUrl = $client->createAuthUrl();
        }
    }


    /**
    * Parse
    *
    * @return    void
    */
    private function parse()
    {
        $this->tpl->assign('events', $this->events);
        $this->tpl->assign('authUrl', $this->authUrl);
    }
}

?>

When I open this widget-page for the first time, I get directed to google to authenticate the application. When I agree, I get redirected to my application and that's the point where I'm getting:

apiAuthException » Main

Message Error fetching OAuth2 access token, message: 'invalid_grant'
File    C:\wamp\www\Officevibes\library/external\google-api-php-client\src\auth\apiOAuth2.php
Line    105
Date    Thu, 05 Apr 2012 08:34:47 +0000
URL http://localhost/calendar?code=4/YPUpFklKvhEeTcMm4moRth3x49oe
Referring URL   (Unknown)
Request Method  GET
User-agent  Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/535.19 (KHTML, like Gecko) Chrome/18.0.1025.142 Safari/535.19
like image 215
Michiel Avatar asked Apr 05 '12 09:04

Michiel


People also ask

What does Invalid_grant mean?

"invalid_grant" basically means that your refresh token no longer works. The only solution to the problem is to request access again and get a new one. The question should be why is it expiring in the first place.

Does Google OAuth2 refresh token expire?

The Google Auth server issued Refresh tokens never expire — that's the whole point of the refresh tokens. The refresh token will expire (or I should say become unauthorized) when the user revokes access to your application.

What happens during an OAuth2 authentication flow?

OAuth 2.0 Access Tokens and Authorization Code The OAuth 2 Authorization server may not directly return an Access Token after the Resource Owner has authorized access. Instead, and for better security, an Authorization Code may be returned, which is then exchanged for an Access Token.


2 Answers

You should reuse the access token you get after the first successful authentication. You will get an invalid_grant error if your previous token has not expired yet. Cache it somewhere so you can reuse it.

like image 193
janmoesen Avatar answered Oct 25 '22 22:10

janmoesen


I was having a similar problem caused by the time on my server being incorrect. Make sure your system clock is synchronised.

like image 32
Sio Avatar answered Oct 25 '22 22:10

Sio