2
votes

I would like to use the oauth2 token permanently in my website.

Using google API, when the user giving permission to manage their google calendar, I am getting the access token from google API. I want to save it in database and use it for the last long.

But it is getting invalid. I tried to refresh the token using the oauth2 refresh token API. But getting the error as follows.

Array ( [error] => invalid_grant [error_description] => Token has been expired or revoked. )

I don't want the user to give the permission each time when he enters the website.

I would also like the admin need to access the user's calendar using this token or any other way if it is.

How can I achieve this?

2

2 Answers

4
votes

Instead trying to get the permanent token, I am using the refresh token option.

When I call the google calendar using tag, I have added the parameter like "access_type=offline" as follows

$login_url = 'https://accounts.google.com/o/oauth2/auth?scope=' . urlencode('https://www.googleapis.com/auth/calendar') . '&redirect_uri=' . CLIENT_REDIRECT_URL . '&response_type=code&client_id=' . CLIENT_ID . '&access_type=offline';

After the user allows, I'll get access_token with refresh_token as response. I am saving those in database. Then everytime, when the user's calendar access by the admin, will get the new access_token using the refresh_token that is stored in the database through the refresh_token api call until the user use the unsynchronize option in my site.

Once the user unsynchronized the calendar, I'll update the database. Problem is resolved.

1
votes

Bottom line is you can't get a permanent token - but you can mitigate the need for your user to re-supply credentials.

The solution depends what grant type you are using (which depends largely on whether your application runs on a server or or a end-user's machine). You mention a website so hopefully you use a grant type which returns a refresh code too.

If your app runs on a server and you get a token via the authorisation code grant then you should be able to also get a refresh token when you get an access token. You can use that refresh token to request new refresh/access tokens on a back-channel, without need of your user, or their credentials.

Effectively you should then have long-lived access to your user's google resources providing the user doesn't revoke access.

If you use other grant types, like implicit grant, then you can't get a refresh token. You will need to regularly obtain a new access token. If your user remains logged-in to google on the device your app is running on then they should not be required to supply their google credentials when you request a new access token, so you won't be constantly pestering them for credentials.