Title: Google API Authentication for server
Tags: php;google-api;oauth-2.0;google-calendar-api
Question: I've been trying to get Google's Calendar API working in a PHP web application, but I'm having a hard time getting authenticated.

What I want to do is to allow users to interact with calendars of a single account known by the server.

Each type of scenario covered in the OAuth 2.0 docs  talks about "user consent" which involves a login form and the individual user logging in, but I want the server itself to authenticate directly and obtain an access token for itself.

Is there some part of OAuth or some alternative mechanism I can use to do this?


Here is the accepted answer: In order to do this, you must go through the steps for user consent and then copy the access tokens it gives you into the PHP code.

The usual procedure for OAuth is like this:


Send user to authentication page.
User comes back with $_GET['code']
Send $_GET['code'] to OAuth server for a token
Store token in database for the user (or session, if it's very short lived)


But when doing it with a single calendar like this, you modify step 4. Instead, you dump the token to screen and copy it into your PHP file as variables, instead of putting it in the database. Then when you go to pass the access token to the server, you just pass the known, static token rather than a dynamic token from the database / session.

Comment for this answer: I've been using this exact method for a calendar since December with no issues, and the events on this calendar update so frequently that I know it's still working. I think access tokens do have a lifetime, but it's measured in months, not days or hours.
Comment for this answer: Thanks, but isn't the access token itself short lived? I'd have to do this manually all the time.
Comment for this answer: This only applies to older oauth1, not current oauth2

Here is another answer: See mathewh's answer here:

How to automate login to Google API to get OAuth 2.0 token to access known user account

The lightbulb for me is when you get the access token you get a refresh_token as well... you use this token to "refresh" your access token once it expires.  

There is no way around a manual authorization step the first time.


{'source': 'StackExchangeDataset', 'subset': 'stackoverflow.com', 'metadata': {'AnswerCount': 2, 'CommentCount': 0, 'ContentLicense': 'CC BY-SA 3.0', 'CreationDate': '2012:00:03/14/12', 'FavoriteCount': 3.0, 'PostTypeId': 1, 'Tags': '<php><google-api><oauth-2.0><google-calendar-api>', 'Title': 'Google API Authentication for server', 'ViewCount': 5647, 'id': 9703700, 'user_AboutMe': '', 'user_AccountId': 1323635.0, 'user_DisplayName': 'andy', 'user_Reputation': 53.0, 'user_Views': 4.0, 'user_id': 1268933.0}}