Youtube oAuth 2.0 API permanent code to retrieve tokens - youtube

Basically my goal is to make a form that allows every visitor of my website to upload a video in the comment section to my OWN channel. Currently I'm using YouTube OAuth version 3 API for it. The problem is every 3600 seconds, the code from YouTube will be expired and we will be redirected to Google OAuth that asks for permission (Example: https://accounts.google.com/o/oauth2/auth?client_id=805j8tubb260venakqj8jq3f6hl9eluu.apps.googleusercontent.com). And we need to manually click the 'allow' button every time the button expires.
So is it possible to allow access once, and then we dont need to take the code again to give the upload permission to the website visitor?

You should follow KENdi's instructions on how to get the token -- he pretty much pulled it straight from the docs. But, you should only have to do that once. The trick is to save the refresh_token somewhere, and then use that to get a new access token before you want to upload a video. Here's my quick and dirty NodeJS solution:
function getAccessToken () {
const options = {
method: 'POST',
uri: 'https://accounts.google.com/o/oauth2/token',
form: {
client_id: 'YOUR_CLIENT_ID',
client_secret: 'YOUR_CLIENT_SECRET',
refresh_token: 'YOUR_REFRESH_TOKEN',
grant_type: 'refresh_token'
}
}
return request(options)
.then(body => JSON.parse(body));
}
getAccessToken.then((token) => uploadSomeYoutubeVideo());

Try to check if you follow the steps/process here in this documentation.
1. Register your application as an installed application
2. Request an access token
3. User consent decision
In this step, the user decides whether to grant your application the ability to make API requests that are authorized as the user. Google's authorization server displays the name of your application and the Google API services that it is requesting permission to access with the user's authorization credentials. The user can then consent or refuse to grant access to your application.
4. Handle response from Google
5. Exchange authorization code for refresh and access tokens
6. Process response and store tokens
Here, Google will respond to your POST request by returning a JSON object that contains a short-lived access token and a refresh token.
{
"access_token" : "ya29.AHES6ZTtm7SuokEB-RGtbBty9IIlNiP9-eNMMQKtXdMP3sfjL1Fc",
"token_type" : "Bearer",
"expires_in" : 3600,
"refresh_token" : "1/HKSmLFXzqP0leUihZp2xUt3-5wkU7Gmu2Os_eBnzw74"
}
NOte: Your application should store both values in a secure,
long-lived location that is accessible between different invocations
of your application. The refresh token enables your application to
obtain a new access token if the one that you have expires. As such,
if your application loses the refresh token, the user will need to
repeat the OAuth 2.0 consent flow so that your application can obtain
a new refresh token.
Access tokens periodically expire, so it need to be refreshed. When an access token expires, your application may be able to use a refresh token to obtain a new, valid access token. Server-side web applications, installed applications, and devices all obtain refresh tokens during the authorization process.
Note that tokens might stop, no longer work or
expire
if:
The user has revoked access.
The token has not been used for six months.
The user account has exceeded a certain number of token requests.

Related

how to use oauth2 token permanently?

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?
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.
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.

Refreshed Token could be revoked 50 times per account

I tried to add YouTube Video from the third party and After one day, I got the success in doing so. But While uploading a video the access token is required and in order to get that access token the user must be logged in. And the expiration time for that access token is 3600 seconds( 1 hr).
Now, There are some of my questions regarding this.
Is there anyway, by which I can refresh access token.
If some one has G Suite account, then Is there any special values for expiration time, or it remains the same?
As per the documentation, I can have maximum 50 tokens, So is there any alternative for it, So that I can get valid token after 50 requests.
To answer your question for number 1, you can check the documentation here.
Access tokens periodically expire. You can refresh an access token
without prompting the user for permission (including when the user is
not present) if you requested offline access to the scopes associated
with the token.
If you use a Google API Client Library, the client object refreshes the access token as needed as long as you configure that
object for offline access.
If you are not using a client library, you need to set the access_type HTTP query parameter to offline when redirecting the
user to Google's OAuth 2.0 server. In that case, Google's
authorization server returns a refresh token when you exchange an
authorization code for an access token. Then, if the access token
expires (or at any other time), you can use a refresh token to obtain
a new access token.
Requesting offline access is a requirement for any application that
needs to access a Google API when the user is not present. For
example, an app that performs backup services or executes actions at
predetermined times needs to be able to refresh its access token when
the user is not present. The default style of access is called online.
About the G Suite account, it was stated 24 Hours in the documentation. Note:
In this SO post answer, the function of Access Token and Refresh Token was discussed.
I am not sure if there are ways to alter the limits because of security reasons.
To clearly differentiate these two tokens and avoid getting mixed up,
here are their functions given in The OAuth 2.0 Authorization
Framework:
Access Tokens are issued to third-party clients by an authorization server with the approval of the resource owner. The
client uses the access token to access the protected resources hosted
by the resource server.
Refresh Tokens are credentials used to obtain access tokens. Refresh tokens are issued to the client by the authorization server
and are used to obtain a new access token when the current access
token becomes invalid or expires, or to obtain additional access
tokens with identical or narrower scope.

Getting refresh tokens from Google with OAuth.io

I am trying to get access tokens from OAuth.io for any Google based provider however whenever I authenticate I get an access_token but no refresh_token. I have chosen offline for the access_type but still no joy.
I have tried looking through the documentation for a solution but it barely covers anything related to the refresh token.
To get the refresh token from Google, you need 2 things:
The offline option
cf https://developers.google.com/accounts/docs/OAuth2WebServer
"A token that may be used to obtain a new access token. Refresh tokens are valid until the user revokes access. This field is only present if access_type=offline is included in the authorization code request."
The option approval_prompt set to "force"
cf https://developers.google.com/accounts/docs/OAuth2WebServer
"Important: When your application receives a refresh token, it is important to store that refresh token for future use. If your application loses the refresh token, it will have to re-prompt the user for consent before obtaining another refresh token. If you need to re-prompt the user for consent, include the approval_prompt parameter in the authorization code request, and set the value to force."
so your script should look something like
OAuth.popup('google', {
authorize: {
approval_prompt: 'force'
}
}).then(function(google) {
console.log(google.refresh_token)
//send the refresh token to your server
})
If you are working client-side (Javascript / iOS / Android / Phonegap), you may also need to activate the following option: Send refresh token to front-end in the OAuth.io dashboard > General > advanced option to allow your client side SDK to retrieve the refresh token
https://jsfiddle.net/Lqyc5jpw/

What is the Youtube OAuth 2.0 user token validity period?

I read the documentation in the Youtube developers website it does not talk about any validity.
Does the OAuth 2.0 standards define any validity period or is the authorization token valid till the user revokes it manually ?
The OAuth spec defines that the token should expire shortly after its granted, so will it expire after I get the
access and refresh tokens ?
And can I use this access token for all future API requests or do I need to get a new token periodically ?
I'm assuming you are talking about the authorization code, you're mixing the terms a bit here.
From the OAuth 2.0 draft:
The authorization code MUST expire shortly after it is issued to mitigate the risk of leaks. A maximum authorization code lifetime of 10 minutes is RECOMMENDED. The client MUST NOT use the authorization code more than once. If an authorization code is used more than once, the authorization server MUST deny the request and SHOULD revoke (when possible) all tokens previously issued based on that authorization code.
After using it once for getting the access token, you can not use it again. You also don't need to retrieve an authorization code periodically. You do this only when you have no access token for a user, but want to request his data.
Your access token some time expires. You know when by either looking at the expires_in value that got send with it, or by doing a request to the API and getting an access token expired error back. Then you can use the refresh token to get a new access token without the user being involved.
Very useful step-by-step guide about how to get access and fresh tokens and save them for future use using YouTube OAuth API v3.
PHP server-side YouTube V3 OAuth API video upload guide.
The good thing is, you do not need to worry about the expiry of the tokens, as the script in this guide checks, saves, and updates the token in a txt file for future access.
{"access_token":"XXXXXXXXX","token_type":"Bearer", "expires_in":3600, "refresh_token":"XXXXXXX", "created":000000}
We use at http://presentationtube.com and it works fine with thousands of users.

google oauth2: re-acquiring a refresh_token for an authorized user on a web server application

I'm using oauth2 on a web server and the flow works flawlessly (https://developers.google.com/accounts/docs/OAuth2WebServer).
However, I have some situations in which I need to re-acquire a refresh_token (let's say for example that the refresh_token has been "lost").
In this case when I go through stages 1&2 again I only get an access_token and not a refresh_token.
If the user revokes permission through his google account console and goes through stages 1&2 again I will get a new refresh_token.
Is this known oauth2 behavior? is there a way to force a new refresh_token or getting the same one again?
From https://developers.google.com/accounts/docs/OAuth2WebServer:
Important: When your application receives a refresh token, it is important to store that refresh token for future use. If your application loses the refresh token, it will have to re-prompt the user for consent before obtaining another refresh token. If you need to re-prompt the user for consent, include the approval_prompt parameter in the authorization code request, and set the value to force.
Butter Answer is here. You have to add parameter approval_prompt=force in your post request for token.

Resources