StefanHayden
StefanHayden

Reputation: 3669

Youtube API: Is there a way to refresh an access_token in the client side v3 api?

https://developers.google.com/youtube/v3/guides/authentication

POST /o/oauth2/token HTTP/1.1
Host: accounts.google.com
Content-Type: application/x-www-form-urlencoded

client_id=21302922996.apps.googleusercontent.com&
client_secret=XTHhXh1SlUNgvyWGwDk1EjXB&
refresh_token=1/6BMfW9j53gdGImsixUH6kU5RsR4zwI9lUVX-tqf8JXQ&
grant_type=refresh_token

The developer documentation lists a way to refresh an access_token on the back end. Is there a way to do this with the front end javascript calls?

Upvotes: 1

Views: 1303

Answers (1)

Jeff Posnick
Jeff Posnick

Reputation: 56084

If you're using the client-side web applications flow, which is appropriate if you're writing code in JavaScript that runs in the browser, then there's no way to get back a refresh token and periodically refresh it to get an access token. The accounts.google.com server doesn't support CORS, for one thing, so it's not possible to send the HTTP POST refresh request from your JavaScript.

What you can take advantage of is the approval_prompt=auto parameter behavior, which means that if a user has previously authorized access to your OAuth 2 client id for the same scopes, requesting a new access token can be done without any user intervention. So you can effectively get new access tokens indefinitely.

I'd highly recommend letting the Google APIs JavaScript client library handle this for you. In addition to the samples in the docs, you can take a look at this simple example which shows how you can handle the OAuth 2 flow in a way that only requires initial authorization.

Upvotes: 3

Related Questions