Domanda

Ho esaminato l'OAUTH .NET Google API per autenticare tramite OAuth e utilizzare le API di Google Drive.

In particolare, voglio usare un token di aggiornamento che ho già memorizzato per usarlo per istanziare un servizio googledrive.

Ho trovato campioni come https://code.google.com/p/google-api-dotnet-client/source/browse/tasks.simpleoauth2/program.cs?repo=samples

che sembra usare "googlewebauthorizationbroker.authorizeasync", ma non sono sicuro di come posso usare quel metodo con un token di aggiornamento piuttosto che i segreti del cliente che sembra essere alimentarlo in questo esempio.

È stato utile?

Soluzione

Se ti capisco correttamente, stai chiedendo come puoi creare un nuovo servizio Google, in base a un token di aggiornamento esistente.

Quindi, puoi fare quanto segue:

var token = new TokenResponse { RefreshToken = "YOUR_REFRESH_TOKEN_HERE" }; 
var credentials = new UserCredential(new GoogleAuthorizationCodeFlow(
    new GoogleAuthorizationCodeFlow.Initializer 
    {
      ClientSecrets = [your_client_secrets_here]
    }), "user", token);
.

Quindi è possibile passare le credenziali all'inizializzazione del servizio.

facendo quanto sopra, googleauthorizationcodeflow otterrà un nuovo token di accesso in base ai tuoi secretti di token e client.

Nota che è necessario disporre dei segreti dei clienti, senza che, non sarai in grado di ottenere un token di accesso.

Altri suggerimenti

Il client_secrets.json contiene l'ID client e il segreto del cliente (che ha le tue informazioni OAuth 2.0 per la tua applicazione).

Penso che questo articolo spieghi meglio come puoi oauth 2.0 per accedere a API di Google Apps in particolare se stai costruendo un'applicazione Web.

https://developers.google.com/accounts/docs/oauth2webserver

Se sei interessato a un esempio di codifica, c'è uno in Stackoverflow: API Google+: Come posso utilizzare RefreshtoKens per evitare di richiedere l'accesso Ogni volta che la mia app lancia?

GooglewebauthorizationBroker richiede di inviarlo un implimozione di IdataStore in questo caso FiledataStastore viene inviato.FiledataStore memorizza i dati in% AppData%.Se vuoi usare un aggiornamento che hai salvato da qualche altra parte è necessario creare la tua imprimitazione di Idatastore.

Il codice per il DataStore attuale sono un po 'lungo da pubblicare qui. http://daimto.com/google-oauth2-csharp/

Allora lo usi proprio come vorresti il filedatastore

//Now we load our saved refreshToken.
StoredResponse myStoredResponse = new StoredResponse(tbRefreshToken.Text);
// Now we pass a SavedDatastore with our StoredResponse.
 using (var stream = new FileStream("client_secrets.json", FileMode.Open,
        FileAccess.Read))
  {
     GoogleWebAuthorizationBroker.Folder = "Tasks.Auth.Store";
     StoredCredential = GoogleWebAuthorizationBroker.AuthorizeAsync(
     GoogleClientSecrets.Load(stream).Secrets,
     new[] { DriveService.Scope.Drive,
     DriveService.Scope.DriveFile },
     "user",
      CancellationToken.None,
      new SavedDataStore(myStoredResponse)).Result;
     }
.

C'è un progetto di esempio allegato a quel tutorial.

Per utilizzare il token di aggiornamento:

var init = new GoogleAuthorizationCodeFlow.Initializer
{
    ClientSecrets = new ClientSecrets
    {
        ClientId = "OAuth_Client_ID_From_GoogleAPI",
        ClientSecret = "OAuth_Client_Secret"
    },
    Scopes = new string[] {"MY_SCOPES"}
};
var token = new TokenResponse { RefreshToken = "MY_REFRESH_TOKEN" };
var credential = new UserCredential(new Google.Apis.Auth.OAuth2.Flows.AuthorizationCodeFlow(init), "", token);

//init your Google API service, in this example Google Directory
var service = new DirectoryService(new BaseClientService.Initializer()
{
    HttpClientInitializer = credential,
    ApplicationName = "",
});
.

Cosa succede se non hai un token di aggiornamento?Il più semplice è seguire le istruzioni sui documenti di Google SDK.Primo Scarica le tue credenziali dal progetto Google API.Nome del file credentials.json.Quindi eseguire il codice:

using (var stream =
    new FileStream("credentials.json", FileMode.Open, FileAccess.Read))
{
    // The file token.json stores the user's access and refresh tokens, and is created
    // automatically when the authorization flow completes for the first time.
    string credPath = "token.json";
    credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
        GoogleClientSecrets.Load(stream).Secrets,
        Scopes,
        "user",
        CancellationToken.None,
        new FileDataStore(credPath, true)).Result;
    Console.WriteLine("Credential file saved to: " + credPath);
}
.

Questo dovrebbe creare una cartella token.json e una cartella interna è un altro file JSON che ha il tuo aggiorna_token.

{
    "access_token" : "asdf",
    "token_type" : "Bearer",
    "expires_in" : 3600,
    "refresh_token" : "XXX",
    "scope" : "https://www.googleapis.com/auth/admin.directory.user.readonly",
    "Issued" : "2019-02-08T12:37:06.157-08:00",
    "IssuedUtc" : "2019-02-08T20:37:06.157Z"
}
.

Preferisco non utilizzare GoogleWebAuthorizationBroker perché avvia automaticamente un browser Web quando Il token non è stato trovato.Preferisco il vecchio modo di ottenere il token di aggiornamento tramite il codice di accesso. Questo è molto simile all'utilizzo di Google OAuthUtil.CreateOAuth2AuthorizationUrl e OAuthUtil.GetAccessToken nell'API OAuth Legacy di Google.

var a = new Google.Apis.Auth.OAuth2.Flows.GoogleAuthorizationCodeFlow.Initializer
{
    ClientSecrets = new ClientSecrets
    {
        ClientId = "asdf",
        ClientSecret = "hij"
    },
    Scopes = Scopes
};
var flow = new Google.Apis.Auth.OAuth2.Flows.AuthorizationCodeFlow(a);
var url = flow.CreateAuthorizationCodeRequest(GoogleAuthConsts.InstalledAppRedirectUri).Build().AbsoluteUri;
Console.WriteLine("Go to this URL and get access code: " + url);

Console.Write("Enter access code: ");
var code = Console.ReadLine();

Console.WriteLine("Fetching token for code: _" + code + "_");
var r = flow.ExchangeCodeForTokenAsync("user", code, GoogleAuthConsts.InstalledAppRedirectUri, CancellationToken.None).Result;
Console.WriteLine(Newtonsoft.Json.JsonConvert.SerializeObject(r));
.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top