C# MVC Upload Video to YouTube using v3 API without OAuth? - c#

I want my users to be able to upload videos to MY YouTube channel under MY YouTube account. Hence I don't really want or need them to authenticate (OAuth) as themselves.
I've seen the examples here: https://developers.google.com/youtube/v3/code_samples/dotnet
All of the code examples I find seem to use OAuth and client secrets to authenticate. Can anybody point me in the direction of a nice tutorial/sample whereby I can upload a video to MY Channel as MYself (using an API key?)?
Thanks.
UPDATE
Well....I'm not even sure if what I've done is right....but here is what I've done:
Went to Credentials for my project:
https://console.developers.google.com/apis/credentials
Created 2 OAuth credenials - one was Web Application and one was Other. I downloaded the JSON for these and added them to my project so I could test each one.
I enabled the YouTube data API here:
https://console.developers.google.com/apis/api/youtube.googleapis.com/overview
I largely took the .Net upload example from here:
https://developers.google.com/youtube/v3/code_samples/dotnet
I also installed the Nuget package for the YouTube API v3
before "var youtubeService =..." I added this:
// This bit checks if the token is out of date,
// and refreshes the access token using the refresh token.
if (credential.Token.IsExpired(SystemClock.Default))
{
if (!await credential.RefreshTokenAsync(CancellationToken.None))
{
Console.WriteLine("No valid refresh token.");
}
}
also created the following class - again, I obtained it from another StackOverflow post - with the aim of creating an offline access token??
public class OfflineAccessGoogleAuthorizationCodeFlow : GoogleAuthorizationCodeFlow
{
public OfflineAccessGoogleAuthorizationCodeFlow(GoogleAuthorizationCodeFlow.Initializer initializer) : base(initializer) { }
public override AuthorizationCodeRequestUrl CreateAuthorizationCodeRequest(string redirectUri)
{
return new GoogleAuthorizationCodeRequestUrl(new Uri(AuthorizationServerUrl))
{
ClientId = ClientSecrets.ClientId,
Scope = string.Join(" ", Scopes),
RedirectUri = redirectUri,
AccessType = "offline",
ApprovalPrompt = "force"
};
}
}
So I've tested it, and the upload eventually 'seems' to work, however:
The code never returns back to the View from await videosInsertRequest.UploadAsync(); and just seems to hang....UPDATE - Fixed. See here: https://www.codeproject.com/Questions/1087360/Youtube-data-API-for-uploading-videos-not-working
The video never actually appears in my channel - i have a feeling YouTube ban it before it's even uploaded? (it's just a test video - nothing sinister - could that be why?)
I have no idea if I am still doing this right.
Any more advice please? I still struggle to believe nobody has a working example of what I'm after. I can't believe that a user....uploading a video to my web server.....and then uploading to my own channel is so difficult!!

First off: It is impossible to upload videos with API keys.
From a technical point of view, API keys are not tied to a specific YouTube channel, but to a Google Cloud Console project. That means even if YouTube allowed API keys as authentication for uploading videos, they wouldn't know which channel to upload to.
For all write actions (e.g. uploading videos), proper authentication via OAuth 2.0 is required. Therefore, there are no tutorials that show how to upload using an API key.
As #Gusman said, you would need to let your users upload to your server, and then your server uploads to YouTube using OAuth credentials.
Regarding "'Installed Application' no longer seems to exist...":
The way you work with API keys and OAuth client IDs/secrets in your code has stayed exactly the same. Google just changed how you create and restrict access to keys in the Cloud Console.
I encourage you to familiarize yourself with the concept of server-side apps that use the YouTube API.
EDIT: to clarify the workflow
You set up a Cloud Console project and an OAuth client ID.
You give your permission to your application that it may upload videos to your channel. Your application will receive tokens (access token and refresh token) as a result.
Users of your application upload their videos to your application server.
Your application takes the user's video (which is now locally on your server) and the tokens from step 2 and uploads the video to YouTube with those tokens.

You must use oAuth, but what you want to skip is the user authentication step.
See this SO answer here
You need to obtain a refresh token and store that in your code along with the OAuth Key and Secret.
As for your "banned" video. If the video was uploaded as 'unlisted' it will not show up until you navigate to your Creator Studio -> Videos list

Related

Azure mobile service auto-login with Xamarin

I'm brand new to Xamarin and playing around with a simple cross-platform app.
The app connects to an Azure Mobile Service, and requires login which I've set up server-side following tutorial: and client-side following tutorial.
Everything works fine! However, the current implementation requires you to login everytime you start the app. How can i cache the user credentials and auto-login as long as you don't log out?
I've tried something like this, but obviously didn't work:
When a user is logging in I save (I'm not calling directly to MobileServiceClient, just showing you a snippet):
var userId = MobileServiceClient.CurrentUser.UserId;
var authToken = MobileServiceClient.CurrentUser.MobileServiceAuthenticationToken
So i store these two strings, and when I next time open the app I try to:
CurrentClient.CurrentUser = new MobileServiceUser(userId);
CurrentClient.CurrentUser.MobileServiceAuthenticationToken = authToken;
As I said this does not seem to be the correct way since it does not work. What is the correct way to cache and auto-login an user?
You need to move over to a CLIENT-FLOW - in client-flow authentication, you use the client SDK provided by the auth provider and then pass that token silently to Azure Mobile Apps to authenticate there. Check out Chapter 2 of my book - http://aka.ms/zumobook

Receiving Refresh Token from Windows Live SDK in Universal Windows App

I'm developing an universal windows app (Windows 10) where I have a "Two-Layered" App: On IoT-Devices (e.g. Raspberry Pi 2) it just displays content, but on all other Devices (PC, Notebook, Smartphone, etc.) you have something like an controller for the displayed data.
One of the features I want to realize is the Windows Live Login in the Controller Part to get Calendar Information in the Display-IoT-Part. For that I give users the opportunity to login with Windows Live as shown below:
LiveAuthClient auth = new LiveAuthClient();
LiveLoginResult loginResult = await auth.LoginAsync(new string[] { "wl.signin", "wl.calendars", "wl.offline_access" });
if (loginResult.Status == LiveConnectSessionStatus.Connected)
{
//Save the AccessToken from loginResult.Session.AccessToken
TokenHandler.Save(loginResult.Session.AccessToken); //AccessToken is quite accessable right here
//But as far as I know I should save the RefreshToken, but the Session has no field for it
}
So my proplem is, that I don't get a field from the LiveConnectSession where the RefreshToken could be stored, but all articles I read are telling, that I just need to add wl.offline_access to the scopes for receiving an RefreshToken.
I'm not very familiar with OAuth2.0 and SDKs / APIs are building on OAuth, so does someone knows anything, what I'm doing wrong or how I have to handle it?
I'm really thankful for all well meant and helpful answers!
PS: I'm using the Live SDK 5.6 and not the new OneDrive API, because it has no access to Calendar Information
wl.offline_access
in this case it's talking about user authorization and allowing the app to have the user's authorization to work when they're not present (when the user is offline, instead of the computer/device).
This doesnt mean the app would login user when system is offline but would request user to allow app to work when user isn't present.
Even I had used the Live SDK to fetch user data in one of my earlier projects and but for calendar had to use Office365. Now you can even make use of Outlook API
Though we do get Access Token using loginResult.Session.AccessToken but I dont think a refreshToken is generated for WinRT app.

Is it possible to retrieve a list of Facebook friends via Server Side?

I have no idea how to start to retrieve my Facebook friends using the Facebook API. I have read the Graph API docs.
Secondly, I'm doing TDD so I want to start with my test cases.
At first, these will be integration tests because I have to integrate the real life Facebook api. After that works, I'll mock out these tests to make them unit tests.
So this is why I'm stuck. Please assume that I have a Facebook account (eg. email + password) so I can authenticate and then use the access token to get my friends.
UPDATE:
I also do have an FB App already setup (eg. app id / app secret).
The first thing that you need to do to get the list of friends, or any other api request on the behalf of the user, is to authenticate the user and get a user access token.
There are two authentication flows:
Client-Side: will result with a short lived access token (expires within a few hours) which you can then extend (on the server side) for a long lived using the new endpoint.
Server-Side: results with a long lived access token for about 60 days.
It will probably be hard to do that with TDD (at least at first), and so you might want to use one of the following facebook tools which will generate the access token for you:
Access Token Tool: gives you a list of `access tokens for all your apps bound to your own user'. Per application you get both a user token and an app token.
Graph API Explorer: Select your application at the top right corner and then click the "Get Access Token" button, then select the permissions you need and approve it, when the dialog closes you'll see the access token in the field.
With the access token that you get you can start querying the api.
To get the list of friends simply issue a request to me/fiends as explained in the Friends connection of the User object documentation.
I'm not a C# developer, but I'm aware of this C# SDK for Facebook, it should (like all other facebook SDKs) have implemented most of the work for you for sending the api requests and parsing the returned data.
From a quick look at their getting started documentation it should look something like:
var accessToken = "THE ACCESS TOKEN YOU HAVE";
var client = new FacebookClient(accessToken);
dynamic me = client.Get("me/friends");
...

How to get Google Analytics data using OAuth?

Hy guys, we are developing a system which will provide users with access to Google Analytics. I'm trying to implement it in the way so user don't need to enter their Google login credentials on our site, so trying to get it work using their login.
I have a solution which gets analytics using user's email and password. I'm looking for a solution which will not require user's email and password but can not find anything.
How can it be done? any advices or links will be appreciated.
thanks
Ok, guys, after a few days of struggle I finally figured this out. There is no documentation on the Internet and people who had done it before did not want to share their success by some reason. I found this discussion which helped me.
To make it work you will need DotNetOpenAuth from http://www.dotnetopenauth.net/ and gdata from http://code.google.com/p/google-gdata/
so
using DotNetOpenAuth.ApplicationBlock;
using DotNetOpenAuth.OAuth;
using Google.GData.Client;
using Google.GData.Analytics;
In DotNetOpenAuth there is sample project named OAuthConsumer which you need.
Change it to requiest authorization for Analytics:
GoogleConsumer.RequestAuthorization(google, GoogleConsumer.Applications.Analytics);
This will get you Token and Token secret.
You can use them like this:
GOAuthRequestFactory requestFactory = new GOAuthRequestFactory("cp", TokenManager.ConsumerKey); //ConsumerKey actually is the name of web application
requestFactory.ConsumerKey = TokenManager.ConsumerKey;
requestFactory.ConsumerSecret = TokenManager.ConsumerSecret;
requestFactory.Token = AccessToken;
requestFactory.TokenSecret = TokenManager.GetTokenSecret(AccessToken);
requestFactory.UseSSL = true;
AnalyticsService service = new AnalyticsService(requestFactory.ApplicationName); // acually the same as ConsumerKey
service.RequestFactory = requestFactory;
const string dataFeedUrl = "https://www.google.com/analytics/feeds/data";
DataQuery query1 = new DataQuery(dataFeedUrl);
This service you can use like here or here
And the last thing, you WILL NOT be available to try and test it on localhost so you will need a domain which MUST be registered with Google here in order to get consumer key and secret
There's a .NET/C# class for Google Data authentication that can be used to access the Google Analytics Data Export API (since the API is part of the Google Data standard, though you might need to make Google Analytics specific adjustments.)*
The authentication is best managed by creating a Google Registered Application, as this allows you to make the authentication without security warnings (and, for that matter, security lapses).
There are three forms of supported authentication; the 'secure'/passwordless ones are OAuth and AuthSub (which is the Google-proprietary version of OAuth); the hardcoded username and password version is referred to by Google as 'ClientLogin', and is not considered secure or ideal for multiple-user applications.
*(Since you tagged the question .netc#)
Edit: More details on using AuthSub or OAuth with the .NET library:
AuthSubSupport: http://code.google.com/p/google-gdata/wiki/AuthSubSupport
Code Samples on how to use the libraries for OAuth authentication: http://code.google.com/apis/gdata/docs/auth/oauth.html#2LeggedOAuth (Click the .NET tab).
Basics of working with OAuth are here: http://code.google.com/apis/accounts/docs/OpenID.html#working
Authenticating with OAuth: http://code.google.com/apis/accounts/docs/OAuth.html
After you authenticate a user with OAuth, you will have the request token that works like the one you get back from Google's login API. From there, it should be the same as username/password.
I don't think you need to mess with OAuth.
The google analytics api lets you pass credentials. Just start from this data feed example.
http://code.google.com/p/google-gdata/source/browse/trunk/clients/cs/samples/Analytics_DataFeed_Sample/dataFeed.cs
// Configure GA API and do client login Authorization.
AnalyticsService asv = new AnalyticsService("gaExportAPI_acctSample_v2.0");
asv.setUserCredentials(clientUser, clientPass);
Download the client library here
http://code.google.com/apis/analytics/docs/gdata/gdataLibraries.html
To get a feel for data queries, play with this and then copy the values into the example above
http://code.google.com/apis/analytics/docs/gdata/gdataExplorer.html

ASP.NET & Facebook Connect - How To Post To User's Wall Using Graph API?

I've integrated my website with Facebook Connect, authorization/single-sign on all working great.
Now im trying to post something to the user's wall, which im having some problems with.
First of all, im using the "old" JavaScript API (FeatureLoader.js).
These are the Graph API URL's im using:
private const string UserDetails_Url = #"https://graph.facebook.com/{0}?access_token={1}";
private const string Feed_Url = #"https://graph.facebook.com/{0}/feed?access_token={1}";
private const string TokenExchange_Url = #"https://graph.facebook.com/oauth/access_token?{0}";
I'm using the TokenExchange_Url URL to receive the unique user OAuth token to make calls with.
This is working fine, because a) i receive the token back, and b) i can issue HTTP Get Requests to the Graph API (i.e UserDetails_Url) and it works fine.
But, i cannot Post to the User's wall using the Feed_Url.
I'm pretty sure the issue is i haven't got the appropriate user permissions to post to a wall (i.e facebook-side setting).
Now, i realise i can use the fbPublish API method client-side to do this, but i want to do it server-side with the Graph API.
I wont bother showing my code which attempts the call to the Graph API to post to the user's wall, as its pretty straightforward (HttpWebRequest, set method to "POST', set content type/length, write bytes to Stream, etc).
I think the problem is i need the user to grant my aplpication "publish_stream" extended permissions.
The Facebook Graph API doco says to do this in your authorization request:
https://graph.facebook.com/oauth/authorize?
client_id=...&
redirect_uri=http://www.example.com/callback&
scope=user_photos,user_videos,publish_stream
Which confuses me because im using the following URL to get the OAuth token:
https://graph.facebook.com/oauth/access_token?bunchofqsparams
Am i using the wrong Token Exchange URL? Why is there two different URL's to seemingly get the same piece of information?
Yes - i have read the Facebook API doco (numerous times), and yes i have read other similar SO questions, but they all result in using the client-side API to publish to wall, i want to do it server side.
For the actual "Facebook Connect" button, i'm using the standard FBML:
<fb:login-button length="long" size="medium" autologoutlink="false" background="light" onlogin="facebookLogin('/login')" class=" fb_login_not_logged_in FB_login_button FB_ElementReady"><a id="RES_ID_fb_login" class="fbconnect_login_button"><img id="RES_ID_fb_login_image" src="http://static.ak.fbcdn.net/rsrc.php/zB6N8/hash/4li2k73z.gif" alt="Connect"></a></fb:login-button>
When i click this (and not logged into Facebook), it pops up a window which the user can login. But it doesnt have the "Request Extended Permissions" dialog - shouldnt it? Or is that another popup i need to manually trigger?
So to sum up, here are my questions:
How do i grant extended permissions to publish to the user's wall?
What is the correct URL for obtaining an OAuth token?
Is there a definitive source for showing how to post to a user's wall using server-side Graph API calls?
As i presumed, i was missing a call to the client-side API to request extended permissions. (ie publish_stream).
I had a simple JavaScript function which was executed as part of the "onlogin" attribute of the FBML Login control.
Previously, i was simply doing a redirect (which would then do a single-sign-on in the server-side code).
Now, im doing this:
function postLogin(targetUrl) {
FB.Facebook.apiClient.users_hasAppPermission('publish_stream', function(result) {
if (result == 0 || result == null) {
FB.Connect.showPermissionDialog('publish_stream', function() { redirectTo(targetUrl); });
} else {
redirectTo(targetUrl);
}
});
}
Translated to english:
// On "Facebook Connect" click (which passes in a redirect URL)
// Check if user has 'publish-stream' permissions
// If they do, just redirect.
// If they dont, show a dialog requesting that permission, then redirect.
Now the server-side Graph API calls all work fine.
So to answer my own original three questions:
How do i grant extended permissions to publish to the user's wall?
Answer: make use of the client-side JavaScript API function 'FB.Connect.showPermissionDialog' to show the popup, and 'FB.Facebook.apliClient.users_hasAppPermission' to check if they have the permission.
What is the correct URL for obtaining an OAuth token?
Answer: I still believe it is "https://graph.facebook.com/oauth/access_token?{0}", but "https://graph.facebook.com/oauth/authorize?{0}" might be able to be used for a server-side authentication/authorization process.
Is there a definitive source for showing how to post to a user's wall using server-side Graph API calls?
Answer: If there was, i wouldnt have to had asked this question - so the answer in short, is no. =)
Advice to anyone starting Facebook Connect work, try to avoid the "Old JavaScript API". Do as much as you can server-side (Graph API), and only use the client-side JavaScript API for the initial handshake (cross domain receiver).

Categories

Resources