Youtube analytics example: Keep google account signed in - javascript

I'm working with this Oauth2 example from Youtube API's documentation: https://developers.google.com/youtube/v3/code_samples/javascript?hl=es-419
The problem is: every time I execute a request it asks me for sign in with a google account.
The question is: how can I keep the user signed in? With long access token or something like that.
I'm working with a laravel app.
Thanks in advance.

You need to implement OAuth 2.0 Authorization.
The YouTube Data API supports the OAuth 2.0 protocol for
authorizing access to private user data. The list below explains some
core OAuth 2.0 concepts:
Here are some important points from YouTube API.
When a user first attempts to use functionality in your application that requires the user to be logged in to a Google Account or YouTube
account, your application initiates the OAuth 2.0 authorization
process.
Your application directs the user to Google's authorization server. The link to that page specifies the scope of access that your
application is requesting for the user's account. The scope specifies
the resources that your application can retrieve, insert, update, or
delete when acting as the authenticated user.
If the user consents to authorize your application to access those resources, Google returns a token to your application. Depending on
your application's type, it either validates the token or exchanges it
for a different type of token.
For example, a server-side web application exchanges the returned
token for an access token and a refresh token. The access token lets
the application authorize requests on the user's behalf, and the
refresh token lets the application retrieve a new access token when
the original access token expires.
Note: Important: You need to obtain authorization credentials in the Google Developers Console to be able to use OAuth 2.0
authorization.
Follow the steps in this documentation to obtain authorization credentials.
Your application must have authorization credentials to be able to use
the YouTube Data API. This document describes the different types of
authorization credentials that the Google Developers Console
supports. It also explains how to find or create authorization
credentials for your project.

Related

app.askForSignIn(); not working at all

Sign in intent doesn't work at the moment as clearly explained in the docs, it's just something you can use for test in the emulator, but it's not available in production.
My case is I'm using account linking and my token expires after one day, so if the user doesn't interact with the assistant, the token will no longer be valid. Then if the token is proved as invalid on the webhook I want to send back 'please link your account again' to the assistant from the webhook.
There is a method app.askForSignIn(); which seems similar to what I need but it looks like it is not available for Dialogflow and only available for the SDK.
So what I have done is:
Make an intent in Dialogflow with the name actions.intent.SIGN_IN and added actions_intent_SIGN_IN event to it
When any request comes to the webhook I check the token, then if I encounter an invalid token I call app.askForSignIn();
What is happening:
The app just left the conversation e.g: test app left the conversation
When I say again "talk to test app" it is behaving like the account is linked and does not ask for account linking until I manually reset the whole app using the reset button from test console
Update:
I tried to use the code snippet from the doc (https://developers.google.com/actions/reference/nodejs/AssistantApp#askForSignIn)
and it is not working as well, here is the response from the simulator when I call app.askForSignIn(); from the webhook
You can have 2 tokens, one being the access token, which is short-lived, and the other being the refresh token which is long-lived.
So, When Google needs to call one of your service's APIs, Google uses these endpoints together to get permission from your users to call these APIs on their behalf. A typical OAuth 2.0 session initiated by Google has the following flow:
First, Google opens your authorization endpoint in the user's browser. The user signs in if not signed in already, and grants Google permission to access their data with your API if they haven't already granted permission.
Then, your service creates an authorization code and returns it to Google by redirecting the user's browser back to Google with the authorization code attached to the request.
Next, Google sends the authorization code to your token exchange endpoint, which verifies the authenticity of the code and returns an access token and a refresh token. The access token is a short-lived token that your service accepts as credentials to access APIs. The refresh token is a long-lived token that Google can store and use to acquire new access tokens when they expire.
Finally, Google calls your service's APIs, attaching the access token with each request. Your service verifies that the access token grants Google authorization to access the API, then completes the API call.

Youtube Analytics Offline Access Request when Authenticated as Brand instead of User

Apps Script keeps asking for offline permission with Youtube's API
In Google Apps Script, access to YouTube Reporting API is Forbidden
These are very similar questions however, I am logged in as the owner. The script is in the owner's drive.
My problem
I have been trying to access YouTube Analytics Reports from the Content Owner using GAS(Google Apps Script). There are two accounts a Brand account (holds the data i.e. the video content) and a User account. They both use the same credentials(email & pwd). When authorizing as the user, I get a 403(forbidden). When authorizing as the brand, I am asked to authorize offline access again and again, stopping me from ever being able to make a request.
What I've tried...
Running from Node, using OAUTH Playground tokens, and it works. But I need to stick with GAS.
Using google-script-oauth2: to hard code credentials (similarly to the Node solution) but I couldn't set the refresh token. I got a 401(invalid credentials) - I believe the bearer token was expired
Setting up credentials for and enabling both youtube and youtube analytics APIs
scrapping old credentials and attaching a new project to GAS
removing auth in privacy settings and re-authenticating
toggling a use unsafe scripts option and repeating step 3
switching between contentOwner and channel parameters for the ids param
NOTE: I have two OAUTH2 credentials app script and the web client both are set as Web Applications.
GAS Code
function test(){
YouTubeAnalytics.Reports.query("contentOwner==id", "2017-03-01", "2017-03-31", "likes");
}
Final Thoughts
I believe there is a disconnect between the Brand and the user such that the brand is not given the same access to the OAUTH 2 token. Therefore, it never generates a refresh token. So, the request sees that I am the authorized channel owner but it can't finish the OAUTH flow.
If this is true, why, and how do I fix it? If not, what do you think could be the error?
I just realized the script is in the user account and not the brand account. Would that affect the validation?
Also on the actual channel, the user is listed as the Primary Owner.
I think the problem has to do with Apps Script's limited OAuth scopes. Open the Script Editor and navigate to Resources->Advanced Google Services and you'll see that YouTube's Reporting API is not supported. However, you can get around this by using Service Accounts. They are a pain to set up but once you get them up and running you can explicitly request the scopes required to make authorized calls on the API from GAS.
Here are a few links to get you started:
Using OAuth 2.0 for Server to Server Applications
OAuth 2.0 Scopes for Google APIs
For Using OAuth 2.0 for Server to Server Applications you'll want to scroll down to the section titled Preparing to make an authorized API call. Select the HTTP/REST tab and it should walk you thru the steps you'll need to setup a service account (you'll need to create a JWT - JSON Web Token from your Google console for use in your API calls). You'll also need to retrieve the needed OAuth scope urls for YouTube's Reporting API from the second link provided. Once you're all set up you'll be able to make requests to the API directly from Apps Script using URLFetchApp. Best of luck with your project.
One more thing. Check out Google's API Explorer listing for the YouTube Reporting API. You can get the URL endpoints (and request methods) you'll need to use in your UrlFetchApp calls by playing with the Explorer.
UPDATE 4/28/2017
Also be sure to enable the YouTube Reporting API from your Google API Console.

Is there any way that multiple users can upload to my Youtube channel via Youtube-api

I have used the Youtube-api and also created the oauth-clientId for some demo project. I also used the Client libraries (java & javascript) for uploading videos to my channel and i succeeded. But i don't want to share my login credentials and want my client users to upload videos to my channel. Is there any way, i mean documentation or procedure or youtube-implementations?
Assuming that you are using Java as you said. You should have a refresh token after your application has been authenticated.
The refresh token can be used to request a new access token. You should use this refresh token to allow others to upload to your channel. Note: To my knowledge you cant get a refresh token with the JavaScript client library due to security issues. You need to use a server sided language to do this.
For Refrence:
YouTube does not support service accounts so that wont work. API Key is only used for accessing public data so that wont work either.
I finally found an answer to my question and now my users[whom i give some authorizations] can directly upload to my youtube channel.
As per the comments i received for my question, i came to the conclusion that i have to do it at the server side because of the security issues.
The thing which came to rescue is namely Refresh Token.
I first created a simple application through which i logged & uploaded video [uploading is not necessary] into my youtube account and received the respected refresh token
Then i saved that refresh token through which i created a Credential object manually.
You can check the code provided by google :
UploadVideo.java
Credential credential = Auth.authorize(scopes, "uploadvideo");
This is what i replaced with this and obtained my own refresh token.Refresh token does not expire like normal access token, and is used to generate normal access token when needed. So, refresh token was the key to my question
Then at the backend, the only thing you have to do is just create the Credential manually. You can use this code
getCredential = new GoogleCredential.Builder()
.setJsonFactory(JSON_FACTORY)
.setTransport(HTTP_TRANSPORT)
.setClientSecrets(clientId, clientSecret)
.build()
.setRefreshToken(refreshToken)
// The refresh token here will be the same you received offline.
Here is the official google doc about this concept
Refreshing an access token (offline access)
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.
Server-side web applications, installed applications, and devices all obtain refresh tokens during the authorization process. Refresh tokens are not typically used in client-side (JavaScript) web applications.

OAuth 2.0 token handling. Is there a Server token and client token?

I have a problem understanding the principle handling of oauth 2.0 tokens.
My scenario is, I have a web based frontend backend system with node.js and angular 2.
A user should be able upload a video on this site. Then some additional metadata is created (dosen't matter for this question). When that is done, the user could upload the video to youtube with the additional data by clicking on a button.
My question is how many tokens/credentials are there in this process. The youtube api needs an oauth token. Does the user also have its own token?
Here is the tutorial I used:
https://ionicabizau.net/blog/14-uploading-videos-to-youtube-using-nodejs
As you can see one token for the API is created for local testing. But is this token generated in a different way in a live version? And how is the user of my website recognized. Also via this token? Or do I have to generate a second token for him?
I am not sure what you mean by 'Token'.
In order to access any Google API you will first need to register your application on Google Developer console. You will then need to create Oauth2 credentials. Oauth2 credentials is were your application will request access from a user to access the data on their YouTube account.
On Google Developer console you will need to save the Client id, client secret and the redirect uri. All three will be needed by your code to authenticate the user.
When the user grants your application access to their YouTube data. You will get an access token and a refresh token back from the authentication server. Access tokens are short lived about an hour and are used to make requests (like upload) to the API. A refresh token can be used to request a new access token once the one you have currently has expired.
You will probably end up with the following:
client id, client secrete, redirect uri, and a refresh token.
If you are interested I have a tutorial that is part of my Google Development for beginners tutorial series that explains Oauth2 and how it works.
An access token is generated from the Server side and sent back to client from where the access request is generated. For all the subsequent requests you need to pass the access token which will be verified with the signature of the token saved on the server to check the authentication of valid requests. You will only get 1 access token which will be used.
You can also use "Refresh" tokens in case you need to keep your access tokens valid for longer duration.

Sign in with Google+ flow

I am trying to wrap my head around the G+ Sign-in flow, but I am not sure if I have gotten it right.
I have mainly been looking at this page
Where in that flow can I connect to my own database and fetch things such as username and permissions, and what am I supposed to store as identifier in my database (to quickly identify them next logon)? Should I talk to the G+ API and get their G+ ID and then store that (together with the data I want to store about the user)?
How would the flow look the second time they sign-on?
I need something that will in the end give me the G+ ID (if I used that) so that I can find them in my DB.
The quickest way to get going with Google+ API calls is the Google+ Quickstarts. These samples will get you going with code that should be ready to copy and paste into your applications. I'll shortly discuss the flows demonstrated in the apps.
As with OAuth 2.0, the goal is to get a bearer token (access token in OAuth 2.0) to authorize API calls. The token can be retrieved a number of ways, but the most important for sign-in using the Google+ Sign-In button is code exchange.
The first time a user encounters your site (let's call it sign-up) the flow will be code exchange. The code exchange pattern is:
User reaches your site
User clicks preferred authorization (Google+ Sign-In)
User is presented with consent / authorization screen
Code is returned from JavaScript to the web client
The Web client (HTML/JavaScript) passes the authorization code to your server
The server exchanges the code for a refresh and access token then caches these tokens
At this point, your server has an access token. This means that you can make API calls (e.g. plus.people.get('me'), which gets the signed-in user's profile) to Google based on the user permissions granted to your app.
The user should now be authorized with your server and authentication should happen based on the user's session and so forth. However, now you have a new problem, what happens when the user accesses your site again from a new browser, or otherwise destroys their session?
This is a great time to transition to the next important flow: the authentication (let's just call it "sign-in") flow. For sign-in, you should have the client pass your server an authentication credential (again a bearer token) and then verify the credential before establishing a new session for the user in your database.
The verify token examples on the Google+ Github page demonstrate concise code for sending and verifying ID tokens.
Let's discuss the details of one approach to passing a type of bearer token, the ID token, for authentication.
User signs in to your site
The Google+ Sign-In button returns an ID token in a callback
The client securely passes the ID token to the server
The server verifies the ID token*
The client session is then authenticated
The steps for * are best put in another question, however a typical set of tests includes:
Verify the token's certificate is Google's
Verify the client id is for this app
Verify the user has an account on your site (optional, do this if you need offline access)
Verify the token hasn't expired
Hope that clears things up for the two.
There is one final flow you should be aware of, used for offline API access, token refresh. Token refresh happens when you have a refresh token and an expired access token. For Google's implementation of OAuth 2.0, access tokens expire after 3600 seconds (1 hour). Because these tokens expire, you need to be able to get new access tokens when your stored access tokens expire. To do this, you pass three bits to Google:
Refresh token (retrieved from code exchange)
Client ID (retrieved from the Google developer console)
Client secret (again, retrieved from the Google developer console)
These parts are passed to the Google OAuth server and the server will then return a fresh access token that you can use for offline API access.
There's a wealth of information on this topic, see also:
Using the one-time code flow for Google+ Sign-In
Google+ Developer documentation, Token Verification

Categories

Resources