2015-04-28 7 views
17

Ho lavorato a un sito Web per consentire agli utenti di caricare video su un account YouTube condiviso per un accesso successivo. Dopo tanto lavoro sono stato in grado di ottenere un token attivo e un token di aggiornamento valido.Creazione di un servizio YouTube tramite ASP.NET utilizzando un token di accesso preesistente

Tuttavia, il codice per inizializzare l'oggetto YouTubeService assomiglia a questo:

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, 
}); 

Ho già un gettone, e voglio usare il mio. Sto usando ASP.NET versione 3.5, e quindi non posso fare una chiamata async comunque.

È possibile creare un oggetto YouTubeService senza la chiamata async e utilizzare il mio token personale? C'è un modo in cui posso creare un oggetto credenziale senza il broker di autorizzazioni?

In alternativa, l'applicazione utilizzava l'API di YouTube V2 per un po 'di tempo e aveva un modulo che prendeva un token e ha effettuato un'azione post contro un URI di YouTube che era stato generato insieme al token in API V2. C'è un modo per implementarlo con la V3? C'è un modo per usare Javascript per caricare video e forse un esempio che potrei usare nel mio codice?

+0

Se si utilizza framework 3.5, la libreria con chiamate asincrone non funzionerà, dovrebbe essere compilata con fw 4.0 o superiore ... – Gusman

+0

Sì. Ecco perché voglio una soluzione che non faccia affidamento sulle chiamate asincrone. Non voglio aggiornare il framework se non devo assolutamente farlo. –

+0

Oh mio Dio - è il 2017 e mi sto imbattendo nella stessa cosa. L'hai mai capito? –

risposta

4

NOTA: ho finito con l'upgrade del mio Framework a 4.5 per accedere alle librerie di google.

Per inizializzare in modo programmatico un oggetto UserCredential, è necessario creare un flusso e TokenResponse. Un flusso Richiede un ambito (aka i permessi che stiamo cercando per le credenziali

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); 

Speranza che aiuta

+1

Hai dichiarato che stai utilizzando. 3.5 La libreria client di Google .net funziona con un minimo di .net 4.0 che non viene più aggiornato. .net 4.5 è l'obiettivo attualmente supportato. La biblioteca non funzionerà nel tuo progetto. A meno che tu non abbia aggiornato il framework. Anche questo non funzionerà perché FileDatastore richiede un token di aggiornamento per funzionare e la domanda afferma token di accesso. – DaImTo

+0

È vero, ho dovuto effettuare l'aggiornamento al Framework 4.5. –

+1

Fino al token iniziale. È stato facile. Ho creato un modulo separato per inizializzare quel token e quindi memorizzarlo in un database. Quando è il momento di usarlo, controllo la scadenza del mio token e, se è scaduta, lo aggiorno tramite il token di aggiornamento memorizzato. –

5

Attualmente il funzionario Google .NET client library non funziona con .NET Framework 3.5 (Nota:... Questo è una vecchia domanda la libreria non ha supportato .NET 3.5 dal 2014. Quindi la dichiarazione sarebbe stata valida anche allora.) Detto questo, non si sarà in grado di creare un servizio per la libreria client di Google .NET utilizzando un token di accesso esistente. Inoltre non è possibile crearlo con un token di accesso utilizzando qualsiasi .NET Framework necessario per creare la propria implementazione di Idatastore e carica un token di aggiornamento.

piattaforme supportate

  1. .NET Framework 4.5 e 4.6
  2. .NET core (tramite il supporto netstandard1.3)
  3. di Windows 8 Apps
  4. Windows Phone 8 e 8.1
  5. Librerie di classi portatili

Detto questo, dovrete codificarlo da zero. L'ho fatto ed è fattibile.

Autenticazione:

Hai dichiarato di avere il token di aggiornamento già così io non andrò in come creare questo. La seguente è una chiamata HTTP POST

accesso Refresh richiesta token:

https://accounts.google.com/o/oauth2/token 
client_id={ClientId}.apps.googleusercontent.com&client_secret={ClientSecret}&refresh_token=1/ffYmfI0sjR54Ft9oupubLzrJhD1hZS5tWQcyAvNECCA&grant_type=refresh_token 

Refresh Accesso risposta token:

{ "access_token" : "ya29.1.AADtN_XK16As2ZHlScqOxGtntIlevNcasMSPwGiE3pe5ANZfrmJTcsI3ZtAjv4sDrPDRnQ", "token_type" : "Bearer", "expires_in" : 3600 } 

una chiamata si effettua alla API di YouTube è possibile aggiungere l'accesso token come token al portatore di autorizzazione o puoi portarlo alla fine di qualsiasi richiesta

https://www.googleapis.com/youtube/v3/search?access_token={token here} 

Ho un post completo su tutte le chiamate al server di autenticazione Google 3 legged Oauth2 flow. Io uso solo normale webRequets per tutte le mie chiamate.

// Create a request for the URL. 
WebRequest request = WebRequest.Create("http://www.contoso.com/default.html"); 
// If required by the server, set the credentials. 
request.Credentials = CredentialCache.DefaultCredentials; 
// Get the response. 
WebResponse response = request.GetResponse(); 
// Display the status. 
Console.WriteLine (((HttpWebResponse)response).StatusDescription); 
// Get the stream containing content returned by the server. 
Stream dataStream = response.GetResponseStream(); 
// Open the stream using a StreamReader for easy access. 
StreamReader reader = new StreamReader(dataStream); 
// Read the content. 
string responseFromServer = reader.ReadToEnd(); 
// Display the content. 
Console.WriteLine(responseFromServer); 
// Clean up the streams and the response. 
reader.Close(); 
response.Close(); 

aggiornamento .NET 4+

Se è possibile aggiornare alla versione più recente del .NET utilizzando la libreria sarà molto più facile. Questa è la documentazione ufficiale di Google Web Applications ASP.NET. Ho un codice di esempio aggiuntivo sul mio account github che indica come utilizzare l'API di Google Drive. Google dotnet samples YouTube data v3.

using System; 
using System.Web.Mvc; 

using Google.Apis.Auth.OAuth2; 
using Google.Apis.Auth.OAuth2.Flows; 
using Google.Apis.Auth.OAuth2.Mvc; 
using Google.Apis.Drive.v2; 
using Google.Apis.Util.Store; 

namespace Google.Apis.Sample.MVC4 
{ 
    public class AppFlowMetadata : FlowMetadata 
    { 
     private static readonly IAuthorizationCodeFlow flow = 
      new GoogleAuthorizationCodeFlow(new GoogleAuthorizationCodeFlow.Initializer 
       { 
        ClientSecrets = new ClientSecrets 
        { 
         ClientId = "PUT_CLIENT_ID_HERE", 
         ClientSecret = "PUT_CLIENT_SECRET_HERE" 
        }, 
        Scopes = new[] { DriveService.Scope.Drive }, 
        DataStore = new FileDataStore("Drive.Api.Auth.Store") 
       }); 

     public override string GetUserId(Controller controller) 
     { 
      // In this sample we use the session to store the user identifiers. 
      // That's not the best practice, because you should have a logic to identify 
      // a user. You might want to use "OpenID Connect". 
      // You can read more about the protocol in the following link: 
      // https://developers.google.com/accounts/docs/OAuth2Login. 
      var user = controller.Session["user"]; 
      if (user == null) 
      { 
       user = Guid.NewGuid(); 
       controller.Session["user"] = user; 
      } 
      return user.ToString(); 

     } 

     public override IAuthorizationCodeFlow Flow 
     { 
      get { return flow; } 
     } 
    } 
} 

Il miglior consiglio YouTube non supporta gli account di servizio che dovrai seguire con Oauth2. Finché hai autenticato il tuo codice una volta che dovrebbe continuare a funzionare.

+0

Ho dimenticato di menzionare: attualmente sto usando .NET 4.6.2. Ho accesso a SDK, ma sembra che ci sia un sacco di comportamenti impliciti che devo affrontare in termini di richiesta web. –

+0

Ho qualche codice di autorizzazione che è possibile utilizzare – DaImTo

+0

Ho modificato la mia risposta aggiungendo alcune informazioni su come fare con la libreria. Dovresti davvero aver aperto la tua domanda questa è per 3.5 quindi non è davvero imparentata con la tua. Se hai bisogno di aiuto, fammi sapere che ho anche alcuni tutorial su youtube. – DaImTo

Problemi correlati