Search code examples
javascriptc#asp.netyoutube-apigoogle-oauth

Creating a YouTube Service via ASP.NET using a pre-existing Access Token


I've been working on a Website for users to upload videos to a shared YouTube account for later access. After much work I've been able to get an Active Token, and viable Refresh Token.

However, the code to initialize the YouTubeService object looks like this:

UserCredential credential;
using (var stream = new FileStream("client_secrets.json", FileMode.Open, FileAccess.Read))
{
    credential = await GoogleWebAuthorizationBroker.AuthorizeAsync(
        GoogleClientSecrets.Load(stream).Secrets, 
        // This OAuth 2.0 access scope allows an application to upload files to the
        // authenticated user's YouTube channel, but doesn't allow other types of access.
        new[] { YouTubeService.Scope.YoutubeUpload },
        "user",
        CancellationToken.None
    );
}

var youtubeService = new YouTubeService(new BaseClientService.Initializer()
{
    HttpClientInitializer = credential,
    ApplicationName = Assembly.GetExecutingAssembly().GetName().Name,
});

I've already got a token, and I want to use mine. I'm using ASP.NET version 3.5, and so I can't do an async call anyways.

Is there any way I can create a YouTubeService object without the async call, and using my own token? Is there a way I can build a credential object without the Authorization Broker?

Alternatively, the application used YouTube API V2 for quite some time, and had a form that took a token, and did a post action against a YouTube URI that was generated alongside the token in API V2. Is there a way I can implement that with V3? Is there a way to use Javascript to upload videos, and possibly an example that I could use in my code?


Solution

  • NOTE: I ended up upgrading my Framework to 4.5 to access the google libraries.

    To programatically initialize a UserCredential Object you've got to build a Flow, and TokenResponse. A Flow Requires a Scope (aka the permissions we are seeking for the credentials.

    using Google.Apis.Auth.OAuth2;
    using Google.Apis.Auth.OAuth2.Responses;
    using Google.Apis.Auth.OAuth2.Flows;
    
    string[] scopes = new string[] {
        YouTubeService.Scope.Youtube,
        YouTubeService.Scope.YoutubeUpload
    };
    
    GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow(new GoogleAuthorizationCodeFlow.Initializer
    {
        ClientSecrets = new ClientSecrets
        {
            ClientId = XXXXXXXXXX,  <- Put your own values here
            ClientSecret = XXXXXXXXXX  <- Put your own values here
        },
        Scopes = scopes,
        DataStore = new FileDataStore("Store")
    });
    
    TokenResponse token = new TokenResponse {
        AccessToken = lblActiveToken.Text,
        RefreshToken = lblRefreshToken.Text
    };
    
    UserCredential credential = new UserCredential(flow, Environment.UserName, token);
    

    Hope that helps.