OAuth nelle librerie client del protocollo Google Data

Avviso: questa pagina riguarda le API precedenti di Google, le API Google Data; è pertinente solo alle API elencate nella directory delle API Google Data, molte delle quali sono state sostituite da API più recenti. Per informazioni su una nuova API specifica, consulta la documentazione della nuova API. Per informazioni sull'autorizzazione delle richieste con un'API più recente, vedi Autenticazione e autorizzazione dell'Account Google.

Questo documento descrive come utilizzare le librerie client delle API di Google Data per connettersi all'autenticazione OAuth per applicazioni web di Google.

L'interfaccia OAuth consente a un'applicazione basata sul web di accedere a un servizio Google per conto di un utente. Per mantenere un elevato livello di sicurezza, OAuth consente all'applicazione di ottenere un token di accesso senza mai gestire i dati di accesso all'account dell'utente.

Le librerie client delle API di Google Data forniscono metodi per aiutarti a utilizzare OAuth nella tua applicazione web. Nello specifico, esistono metodi per costruire l'acquisizione di un token di richiesta, l'autorizzazione del token di richiesta e lo scambio del token di richiesta autorizzato con un token di accesso. Le librerie gestiscono anche gli algoritmi di firma necessari quando vengono effettuate richieste a un servizio Google Data.

Pubblico

Questo documento è destinato ai programmatori che vogliono che le loro applicazioni basate sul web accedano ai servizi Google per conto degli utenti, utilizzando le librerie client delle API Google Data.

Questo documento presuppone che tu conosca l'interfaccia OAuth e la procedura generale per incorporare OAuth nella tua applicazione web. Per una descrizione completa del protocollo OAuth, consulta Autenticazione OAuth per applicazioni web o la specifica ufficiale su oauth.net.

Utilizzo di OAuth a tre passaggi e delle API Google Data senza le librerie client

Se vuoi che la tua applicazione web interagisca con un servizio di dati Google utilizzando OAuth come metodo di autorizzazione, trovi tutto ciò che devi sapere in Autenticazione OAuth per applicazioni web. Non è necessario utilizzare le librerie client delle API di Google Data se non vuoi.

Ecco una panoramica di come la tua applicazione potrebbe autenticare un utente utilizzando OAuth:

  1. La tua applicazione effettua una richiesta firmata per recuperare un token di richiesta OAuth iniziale dall'endpoint OAuthRequestToken.
  2. L'applicazione reindirizza l'utente all'URL OAuthAuthorizeToken appropriato per autorizzare il token di richiesta.
  3. Dopo aver concesso l'accesso, l'utente viene reindirizzato alla tua applicazione (l'URL oauth_callback)
  4. La tua applicazione invia una richiesta firmata per eseguire l'upgrade del token di richiesta autorizzato a un token di accesso utilizzando l'endpoint OAuthGetAccessToken.

Le librerie client delle API di dati di Google semplificano questo processo di autorizzazione gestendo vari dettagli per te. Questo documento spiega come.

Registrazione dell'applicazione web

OAuth richiede che tutte le chiamate API siano firmate digitalmente. Google supporta i metodi di firma HMAC-SHA1 e RSA-SHA1. Per firmare le richieste, la tua applicazione deve prima registrarsi su Google. Una volta registrato, Google ti fornirà una chiave consumer (e un secret da utilizzare con HMAC-SHA1) e uno spazio in cui caricare un certificato pubblico.

1. Registrazione del dominio

Segui i passaggi descritti in Registrazione per applicazioni basate sul web.

2. (Facoltativo) Creazione di una coppia di chiave privata / certificato pubblico

Se scegli di utilizzare RSA-SHA1 come oauth_signature_method, devi creare una coppia di chiave privata e certificato pubblico RSA autofirmati. Consulta la sezione Generare una chiave privata autofirmata e un certificato pubblico (di seguito) per esempi su come farlo.

Utilizzo di OAuth a tre passaggi e delle API Google Data: esempi di librerie client

Le sezioni seguenti mostrano esempi di utilizzo dei metodi della libreria client delle API Google Data per seguire i passaggi descritti nella sezione "Utilizzo di OAuth" della documentazione di OAuth. Tutti gli esempi in questo documento presuppongono che il dominio host dell'applicazione sia example.com.

Determinare l'ambito dell'accesso ai dati

Ogni servizio Google definisce un valore scope che determina l'accesso di un token ai dati dell'utente. I valori dell'ambito disponibili sono elencati nelle domande frequenti sui dati di Google. Ad esempio, per utilizzare l'API Document Lists, imposta scope su https://docs.google.com/feeds/, come indicato nelle domande frequenti.

Nota: imposta il valore scope sull'URL più specifico che consente l'accesso di cui hai bisogno. In questo modo si riduce la possibilità di ottenere e divulgare accidentalmente dati personali. Ad esempio, se vuoi accedere al feed privato dell'elenco documenti dell'utente corrente, utilizza l'ambito https://docs.google.com/feeds/default/private/full anziché un ambito più ampio come https://docs.google.com/feeds/, che fornisce l'accesso a tutti i feed dell'elenco documenti.

Token con più ambiti

Per creare token che accedono a più API Google Data, separa ogni ambito con uno spazio. L'esempio seguente crea un token con accesso sia ai dati di Google Documenti che a quelli di Google Calendar di un utente.

scope=https://www.google.com/calendar/feeds/ https://docs.google.com/feeds/
Codifica URL

I caratteri non ASCII che compaiono negli URL, inclusi due punti, barra e spazio, devono essere codificati per l'URL per essere trasmessi tramite HTTP. Le librerie client dell'API Google Data codificano automaticamente i parametri URL, quindi puoi semplicemente utilizzare stringhe non codificate in URL quando assegni valori ai parametri. Ad esempio, puoi effettuare la seguente assegnazione nel codice:

scope=https://www.google.com/calendar/feeds/ https://docs.google.com/feeds/

Quando chiami la libreria client, il parametro scope viene codificato automaticamente nell'URL con il seguente valore:
https%3a%2f%2fwww.google.com%2fcalendar%2ffeeds%2f+https%3a%2f%2fdocs.google.com%2ffeeds%2f

Recupero di un token di richiesta

Java

Per HMAC-SHA1, devi trovare un modo per rendere persistente il secret del token (ottenuto nella risposta) per creare un oggetto token OAuth che viene restituito dalla pagina di approvazione. Per farlo, imposta una variabile di sessione o un cookie.

import com.google.gdata.client.docs.*;
import com.google.gdata.client.authn.oauth.*;

String CONSUMER_KEY = "example.com";
String CONSUMER_SECRET = "abc123doremi";

GoogleOAuthParameters oauthParameters = new GoogleOAuthParameters();
oauthParameters.setOAuthConsumerKey(CONSUMER_KEY);
oauthParameters.setOAuthConsumerSecret(CONSUMER_SECRET);
oauthParameters.setScope("https://docs.google.com/feeds/");
oauthParameters.setOAuthCallback("http://www.example.com/UpgradeToken.jsp");

GoogleOAuthHelper oauthHelper = new GoogleOAuthHelper(new OAuthHmacSha1Signer());
oauthHelper.getUnauthorizedRequestToken(oauthParameters);

Utilizzando RSA-SHA1, oauth_token_secret non viene utilizzato, quindi non è necessario rendere persistente il segreto del token.

import com.google.gdata.client.docs.*;
import com.google.gdata.client.authn.oauth.*;

String CONSUMER_KEY = "example.com";

GoogleOAuthParameters oauthParameters = new GoogleOAuthParameters();
oauthParameters.setOAuthConsumerKey(CONSUMER_KEY);
oauthParameters.setScope("https://docs.google.com/feeds/");
oauthParameters.setOAuthCallback("http://www.example.com/UpgradeToken.jsp");

PrivateKey privKey = getPrivateKey("/path/to/your/rsakey.pk8");

GoogleOAuthHelper oauthHelper = new GoogleOAuthHelper(new OAuthRsaSha1Signer(privKey));
oauthHelper.getUnauthorizedRequestToken(oauthParameters);

...

public static PrivateKey getPrivateKey(String privKeyFileName) {
  File privKeyFile = new File(privKeyFileName);
  FileInputStream fis = new FileInputStream(privKeyFile);
  DataInputStream dis  = new DataInputStream(fis);

  byte[] privKeyBytes = new byte[(int) privKeyFile.length()];
  dis.read(privKeyBytes);
  dis.close();
  fis.close();

  String BEGIN = "-----BEGIN PRIVATE KEY-----";
  String END = "-----END PRIVATE KEY-----";
  String str = new String(privKeyBytes);
  if (str.contains(BEGIN) && str.contains(END)) {
    str = str.substring(BEGIN.length(), str.lastIndexOf(END));
  }

  KeyFactory fac = KeyFactory.getInstance("RSA");
  EncodedKeySpec privKeySpec = new PKCS8EncodedKeySpec(Base64.decode(str));
  return fac.generatePrivate(privKeySpec);
}

PHP

Utilizzando HMAC-SHA1 come metodo di firma:

require_once 'Zend/Oauth/Consumer.php';

session_start();

$CONSUMER_KEY = 'example.com';
$CONSUMER_SECRET = 'abc123doremi';

// Multi-scoped token.
$SCOPES = array(
  'https://docs.google.com/feeds/',
  'https://spreadsheets.google.com/feeds/'
);

$oauthOptions = array(
  'requestScheme' => Zend_Oauth::REQUEST_SCHEME_HEADER,
  'version' => '1.0',
  'consumerKey' => $CONSUMER_KEY,
  'consumerSecret' => $CONSUMER_SECRET,
  'signatureMethod' => 'HMAC-SHA1',
  'callbackUrl' => 'http://myapp.example.com/access_token.php',
  'requestTokenUrl' => 'https://www.google.com/accounts/OAuthGetRequestToken',
  'userAuthorizationUrl' => 'https://www.google.com/accounts/OAuthAuthorizeToken',
  'accessTokenUrl' => 'https://www.google.com/accounts/OAuthGetAccessToken'
);

$consumer = new Zend_Oauth_Consumer($oauthOptions);

// When using HMAC-SHA1, you need to persist the request token in some way.
// This is because you'll need the request token's token secret when upgrading
// to an access token later on. The example below saves the token object as a session variable.
if (!isset($_SESSION['ACCESS_TOKEN'])) {
  $_SESSION['REQUEST_TOKEN'] = serialize($consumer->getRequestToken(array('scope' => implode(' ', $SCOPES))));
}

Utilizzando RSA-SHA1 come metodo di firma:

require_once 'Zend/Crypt/Rsa/Key/Private.php';
require_once 'Zend/Oauth/Consumer.php';

session_start();

$CONSUMER_KEY = 'example.com';
$SCOPE = 'https://docs.google.com/feeds/';

$oauthOptions = array(
  'requestScheme' => Zend_Oauth::REQUEST_SCHEME_HEADER,
  'version' => '1.0',
  'consumerKey' => $CONSUMER_KEY,
  'consumerSecret' => new Zend_Crypt_Rsa_Key_Private(file_get_contents(realpath('/path/to/yourRSAPrivateKey.pem'))),
  'signatureMethod' => 'RSA-SHA1',
  'callbackUrl' => 'http://myapp.example.com/access_token.php',
  'requestTokenUrl' => 'https://www.google.com/accounts/OAuthGetRequestToken',
  'userAuthorizationUrl' => 'https://www.google.com/accounts/OAuthAuthorizeToken',
  'accessTokenUrl' => 'https://www.google.com/accounts/OAuthGetAccessToken'
);

$consumer = new Zend_Oauth_Consumer($oauthOptions);

if (!isset($_SESSION['ACCESS_TOKEN'])) {
  $_SESSION['REQUEST_TOKEN'] = serialize($consumer->getRequestToken(array('scope' => $SCOPE)));
}

Python

Utilizzando HMAC-SHA1 come metodo di firma:

Se utilizzi le classi v2.0+ più recenti basate su GDClient, utilizza:

import gdata.gauth
import gdata.docs.client

CONSUMER_KEY = 'example.com'
CONSUMER_SECRET = 'abc123doremi'
SCOPES = ['https://docs.google.com/feeds/', 'https://www.google.com/calendar/feeds/']  # example of a multi-scoped token

client = gdata.docs.client.DocsClient(source='yourCompany-YourAppName-v1')

oauth_callback_url = 'http://%s/get_access_token' % self.request.host
request_token = client.GetOAuthToken(
    SCOPES, oauth_callback_url, CONSUMER_KEY, consumer_secret=CONSUMER_SECRET)

# When using HMAC-SHA1, you need to persist the request_token in some way.
# You'll need the token secret when upgrading to an access token later on.
# In Google App Engine, you can use the AeSave helper:
# gdata.gauth.AeSave(request_token, 'myKey')

Utilizzando RSA-SHA1 come metodo di firma:

...

f = open('/path/to/yourRSAPrivateKey.pem')
RSA_KEY = f.read()
f.close()

request_token = client.GetOAuthToken(SCOPES, oauth_callback_url, CONSUMER_KEY, rsa_private_key=RSA_KEY)

In alternativa, se utilizzi le classi v1.0 precedenti basate su GDataService, le chiamate sono leggermente diverse:

import gdata.auth
import gdata.docs.service

CONSUMER_KEY = 'example.com'
CONSUMER_SECRET = 'abc123doremi'

client = gdata.docs.service.DocsService(source='yourCompany-YourAppName-v1')
client.SetOAuthInputParameters(gdata.auth.OAuthSignatureMethod.HMAC_SHA1, CONSUMER_KEY, consumer_secret=CONSUMER_SECRET)

req_token = client.FetchOAuthRequestToken()
client.SetOAuthToken(req_token)

Utilizzando RSA-SHA1 come metodo di firma:

...

f = open('/path/to/yourRSAPrivateKey.pem')
RSA_KEY = f.read()
f.close()

client = gdata.docs.service.DocsService(source='yourCompany-YourAppName-v1')
client.SetOAuthInputParameters(gdata.auth.OAuthSignatureMethod.RSA_SHA1, CONSUMER_KEY, rsa_key=RSA_KEY)

SCOPES = ['https://docs.google.com/feeds/', 'https://www.google.com/calendar/feeds/']  # example of a multi-scoped token
req_token = client.FetchOAuthRequestToken(scopes=SCOPES)
client.SetOAuthToken(req_token)

.NET

Utilizzando HMAC-SHA1 come metodo di firma:

using Google.GData.Client;

string CONSUMER_KEY = "example.com";
string CONSUMER_SECRET = "abc123doremi";

// Multi-scoped token.
string SCOPE = "https://www.google.com/calendar/feeds/ https://www.google.com/m8/feeds/";

OAuthParameters parameters = new OAuthParameters() {
  ConsumerKey = CONSUMER_KEY,
  ConsumerSecret = CONSUMER_SECRET,
  Scope = SCOPE,
  Callback = "http://myapp.example.com/access_token",
  SignatureMethod = "HMAC-SHA1"
}

OAuthUtil.GetUnauthorizedRequestToken(parameters);

Utilizzando RSA-SHA1 come metodo di firma:

RSA-SHA1 is not supported yet.

Autorizzazione di un token di richiesta

Per autorizzare un token di richiesta, la tua applicazione deve reindirizzare l'utente all'URL OAuthAuthorizeToken, che gli chiede di accedere al proprio Account Google. Per ulteriori informazioni sull'URL OAuthAuthorizeToken, consulta la documentazione completa sull'autenticazione OAuth per applicazioni web.

Per creare l'URL OAuthAuthorizeToken nella tua applicazione, utilizza quanto segue per ogni libreria client. Tieni presente che questi esempi si basano su quelli precedenti.

Dopo aver creato l'URL della pagina di approvazione, la tua applicazione può utilizzarlo in vari modi per inviare l'utente al gestore OAuthAuthorizeToken. L'approccio più comune è reindirizzare l'utente o mostrare un link a quella pagina.

Java

Per HMAC-SHA1:

String approvalPageUrl = oauthHelper.createUserAuthorizationUrl(oauthParameters);
System.out.println(approvalPageUrl);

Per RSA-SHA1:

String approvalPageUrl = oauthHelper.createUserAuthorizationUrl(oauthParameters);
System.out.println(approvalPageUrl);

PHP

// If on a G Suite domain, use your domain for the hd param (e.g. 'example.com').
$approvalUrl = $consumer->getRedirectUrl(array('hd' => 'default'));
echo "<a href=\"$approvalUrl\">Grant access</a>";

In alternativa, puoi semplicemente reindirizzare all'URL di approvazione:

// If on a G Suite domain, use your domain for the hd param (e.g. 'example.com').
$consumer->redirect(array('hd' => 'default'));

Python

Se utilizzi le classi v2.0+ più recenti basate su GDClient, utilizza:

# req_token is from previous call to client.GetOAuthToken()
domain = None  # If on a G Suite domain, use your domain (e.g. 'example.com').
self.redirect(request_token.generate_authorization_url(google_apps_domain=domain))

Se utilizzi le classi v1.0 precedenti basate su GDataService, la procedura è leggermente diversa.

# req_token is from previous call to client.FetchOAuthRequestToken()
oauth_callback_url = 'http://%s/get_access_token' % self.request.host
self.redirect(client.GenerateOAuthAuthorizationURL(callback_url=oauth_callback_url))

.NET

string authorizationUrl = OAuthUtil.CreateUserAuthorizationUrl(parameters);
Console.WriteLine(authorizationUrl);

Estrazione del token dall'URL di callback

Quando Google reindirizza alla tua applicazione, oauth_token viene aggiunto all'URL "oauth_callback_url" come parametro di ricerca. L'applicazione deve quindi estrarre il valore del token dal parametro di query dell'URL e ristabilire i parametri OAuth.

Le librerie client forniscono metodi pratici per estrarre oauth_token. Questi esempi si basano su quelli precedenti.

Java

Se hai scelto di rendere persistente il segreto del token nell'URL di callback (quando utilizzi HMAC-SHA1):

GoogleOAuthParameters oauthParameters = new GoogleOAuthParameters();
oauthParameters.setOAuthConsumerKey(CONSUMER_KEY);
oauthParameters.setOAuthConsumerSecret(CONSUMER_SECRET);

GoogleOAuthHelper oauthHelper = new GoogleOAuthHelper(new OAuthHmacSha1Signer());
oauthHelper.getOAuthParametersFromCallback(request.getQueryString(), oauthParameters);

L'unica differenza con RSA-SHA1 è il metodo di firma:

GoogleOAuthParameters oauthParameters = new GoogleOAuthParameters();
oauthParameters.setOAuthConsumerKey(CONSUMER_KEY);

PrivateKey privKey = getPrivateKey("/path/to/your/rsakey.pk8");

GoogleOAuthHelper oauthHelper = new GoogleOAuthHelper(new OAuthRsaSha1Signer(privKey));
oauthHelper.getOAuthParametersFromCallback(request.getQueryString(), oauthParameters);

PHP

Questo passaggio non è necessario quando utilizzi la libreria PHP.

Python

Se utilizzi le classi v2.0+ più recenti basate su GDClient, utilizza:

# Recall request_token. In Google App Engine, use AeLoad():
# saved_request_token = gdata.gauth.AeLoad('myKey')

request_token = gdata.gauth.AuthorizeRequestToken(saved_request_token, self.request.uri)

Se utilizzi le classi v1.0 precedenti basate su GDataService, utilizza:

oauth_token = gdata.auth.OAuthTokenFromUrl(self.request.uri)
if oauth_token:
  oauth_token.secret = # TODO: recall saved request_token and set the token secret here.
  oauth_token.oauth_input_params = gdata.auth.OAuthInputParams(
      gdata.auth.OAuthSignatureMethod.HMAC_SHA1, CONSUMER_KEY, consumer_secret=CONSUMER_SECRET)
 client.SetOAuthToken(oauth_token)
else:
  print 'No oauth_token found in the URL'

La procedura è simile per RSA-SHA1, ma senza il secret del token:

oauth_token = gdata.auth.OAuthTokenFromUrl(self.request.uri)
if oauth_token:
  oauth_token.oauth_input_params = gdata.auth.OAuthInputParams(
      gdata.auth.OAuthSignatureMethod.RSA_SHA1, CONSUMER_KEY, rsa_key=RSA_KEY)
 client.SetOAuthToken(oauth_token)
else:
  print 'No oauth_token found in the URL'

.NET

Se hai scelto di rendere persistente il secret del token nell'URL di callback:

OAuthUtil.UpdateOAuthParametersFromCallback(url, parameters);

Eseguire l'upgrade a un token di accesso

L'ultimo passaggio della sequenza di scambio dei token OAuth consiste nell'upgrade del token di richiesta autorizzato a un token di accesso di lunga durata utilizzando l'URL OAuthGetAccessToken, come descritto nella documentazione completa relativa all'autenticazione OAuth per le applicazioni web.

Ecco alcuni esempi che utilizzano ciascuna delle librerie client:

Java

String accessToken = oauthHelper.getAccessToken(oauthParameters);
// You can also pull the OAuth token string from the oauthParameters:
// String accessToken = oauthParameters.getOAuthToken();
System.out.println("OAuth Access Token: " + accessToken);

String accessTokenSecret = oauthParameters.getOAuthTokenSecret();
System.out.println("OAuth Access Token's Secret: " + accessTokenSecret);

PHP

if (!isset($_SESSION['ACCESS_TOKEN'])) {
  if (!empty($_GET) && isset($_SESSION['REQUEST_TOKEN'])) {
    $_SESSION['ACCESS_TOKEN'] = serialize($consumer->getAccessToken($_GET, unserialize($_SESSION['REQUEST_TOKEN'])));
  }
}

Python

Se utilizzi le classi v2.0+ più recenti basate su GDClient, utilizza:

# Upgrade the token and save in the user's datastore
access_token = client.GetAccessToken(request_token)

# If you're using Google App Engine, you can call the AeSave() method to save
# the access token under the current logged in user's account.
#gdata.gauth.AeSave(access_token, token_key)

Se utilizzi le classi v1.0 precedenti basate su GDataService, utilizza:

access_token = client.UpgradeToOAuthAccessToken()  # calls SetOAuthToken() for you

Se utilizzi gdata.gauth.AeSave() su App Engine, il token e il segreto del token verranno memorizzati per te con l'utente attualmente connesso.

.NET

OAuthUtil.GetAccessToken(parameters);

// If you want to extract the OAuth Token/TokenSecret from the OAuthParameters instance:
string accessToken = parameter.Token;
Console.WriteLine("OAuth Access Token: " + accessToken);

string accessTokenSecret = parameter.TokenSecret;
Console.WriteLine("OAuth Access Token's Secret: " + accessTokenSecret);

Nota: se utilizzi HMAC-SHA1, assicurati di salvare il secret del token di accesso insieme al valore del token nel database, altrimenti non potrai ricostruire correttamente i parametri OAuth per un utilizzo successivo.

Utilizzo di un token di accesso

Dopo aver ottenuto un token di accesso, utilizza le chiamate standard della libreria client delle API di dati di Google per interagire con il servizio. La libreria si occuperà di firmare le richieste e includere l'intestazione di autorizzazione corretta. In genere, recupererai il token dell'utente da un cookie o da un database. Questi esempi mostrano come ricostruire i parametri OAuth ed effettuare una chiamata alla libreria client.

Java

Se utilizzi HMAC-SHA1:

  GoogleOAuthParameters oauthParameters = new GoogleOAuthParameters();
  oauthParameters.setOAuthConsumerKey(CONSUMER_KEY);
  oauthParameters.setOAuthConsumerSecret(CONSUMER_SECRET);
  oauthParameters.setOAuthToken(ACCESS_TOKEN);
  oauthParameters.setOAuthTokenSecret(TOKEN_SECRET);

  DocsService client = new DocsService("yourCompany-YourAppName-v1");
  client.setOAuthCredentials(oauthParameters, new OAuthHmacSha1Signer());

  URL feedUrl = new URL("https://docs.google.com/feeds/default/private/full");
  DocumentListFeed resultFeed = client.getFeed(feedUrl, DocumentListFeed.class);
  for (DocumentListEntry entry : resultFeed.getEntries()) {
    System.out.println(entry.getTitle().getPlainText());
  }
  

La differenza con RSA-SHA1 è che non è necessario impostare il secret del token di accesso e la creazione dell'oggetto firmatario è diversa:

  GoogleOAuthParameters oauthParameters = new GoogleOAuthParameters();
  oauthParameters.setOAuthConsumerKey(CONSUMER_KEY);
  oauthParameters.setOAuthConsumerSecret(CONSUMER_SECRET);
  oauthParameters.setOAuthToken(ACCESS_TOKEN);

  PrivateKey privKey = getPrivateKey("/path/to/your/rsakey.pk8");  // See above for the defintion of getPrivateKey()

  DocsService client = new DocsService("yourCompany-YourAppName-v1");
  client.setOAuthCredentials(oauthParameters, new OAuthRsaSha1Signer(privKey));

  URL feedUrl = new URL("https://docs.google.com/feeds/default/private/full");
  DocumentListFeed resultFeed = client.getFeed(feedUrl, DocumentListFeed.class);
  for (DocumentListEntry entry : resultFeed.getEntries()) {
    System.out.println(entry.getTitle().getPlainText());
  }
  

PHP

require_once 'Zend/Gdata/Docs.php';

if (isset($_SESSION['ACCESS_TOKEN'])) {
  $accessToken = unserialize($_SESSION['ACCESS_TOKEN']);
} else {
  exit;
}


/*  Or, you could set an existing token (say one stored from your database). For HMAC-SHA1:
$accessToken = new Zend_Oauth_Token_Access();
$accessToken->setToken('1/AQfoI-qJDqkvvkf216Gc2g');
$accessToken->setTokenSecret('2c26GLW250tZiQ');
*/

$httpClient = $accessToken->getHttpClient($oauthOptions);
$client = new Zend_Gdata_Docs($httpClient, "yourCompany-YourAppName-v1");

// Retrieve user's list of Google Docs
$feed = $client->getDocumentListFeed();
foreach ($feed->entries as $entry) {
  echo "$entry->title\n";
}

Python

Questo snippet presuppone che tu abbia già recuperato un token di accesso (utilizzando HMAC-SHA1) e che tu stia richiamando la chiave/il segreto del token per un utilizzo successivo.

Se utilizzi le classi v2.0+ più recenti basate su GDClient, utilizza:

client = gdata.docs.client.DocsClient(source='yourCo-yourAppName-v1')
client.auth_token = gdata.gauth.OAuthHmacToken(CONSUMER_KEY, CONSUMER_SECRET, TOKEN,
                                               TOKEN_SECRET, gdata.gauth.ACCESS_TOKEN)
feed = client.GetDocList()
for entry in feed.entry:
  print entry.title.text

Se utilizzi le classi v1.0 precedenti basate su GDataService, utilizza:

client = gdata.docs.service.DocsService(source='yourCompany-YourAppName-v1')
client.SetOAuthInputParameters(SIG_METHOD, CONSUMER_KEY, consumer_secret=CONSUMER_SECRET)

# the token key and secret should be recalled from your database
client.SetOAuthToken(gdata.auth.OAuthToken(key=TOKEN, secret=TOKEN_SECRET))

feed = client.GetDocumentListFeed()
for entry in feed.entry:
  print entry.title.text

.NET

Se utilizzi HMAC-SHA1:

OAuthParameters parameters = new OAuthParameters() {
  ConsumerKey = CONSUMER_KEY,
  ConsumerSecret = CONSUMER_SECRET,
  Token = ACCESS_TOKEN,
  TokenSecret = TOKEN_SECRET
}

GOAuthRequestFactory requestFactory = new GOAuthRequestFactory("writely", APPLICATION_NAME, parameters);

DocsService service = new DocsService(APPLICATION_NAME);
service.RequestFactory = requestFactory;

DocumentsListQuery query = new DocumentsListQuery();
DocumentsFeed feed = service.Query(query);
foreach (DocumentEntry entry in feed.Entries) {
  Console.WriteLine(entry.Title.Text);
}

La differenza con RSA-SHA1 è che non è necessario impostare il secret del token di accesso e la creazione dell'oggetto firmatario è diversa:

RSA-SHA1 is not supported yet.

Risorse ed esempi aggiuntivi di OAuth a tre vie

Torna all'inizio

OAuth a due vie

OAuth a due passaggi consente alle applicazioni attendibili di accedere ai dati Google degli utenti senza il loro coinvolgimento diretto. Due gruppi chiave possono utilizzare OAuth a due vie:

Amministratori di dominio G Suite:gli amministratori possono creare script e applicazioni personalizzate che gestiscono i dati utente per il loro dominio tramite le API Google Data. Per informazioni sulla gestione della chiave e del secret associati al tuo dominio G Suite e sulla concessione del controllo dell'accesso globale, vedi "Gestione della chiave e del secret OAuth".

Fornitori di software di terze parti:i fornitori possono offrire applicazioni che utilizzano OAuth a due passaggi per l'integrazione con G Suite. L'accesso per le applicazioni di terze parti può essere concesso nella pagina Gestisci client API o tramite l'installazione da G Suite Marketplace.

Un token di accesso non è necessario in base al normale flusso di autorizzazione (chiamato anche OAuth a tre vie).

I seguenti esempi di librerie client mostrano come configurare il client per utilizzare OAuth a due passaggi utilizzando HMAC-SHA1.

Java

import com.google.gdata.client.docs.*;
import com.google.gdata.client.authn.oauth.*;

String CONSUMER_KEY = "example.com";
String CONSUMER_SECRET = "abc123doremi";

GoogleOAuthParameters oauthParameters = new GoogleOAuthParameters();
oauthParameters.setOAuthConsumerKey(CONSUMER_KEY);
oauthParameters.setOAuthConsumerSecret(CONSUMER_SECRET);

DocsService client = new DocsService("yourCompany-YourAppName-v1");
client.setOAuthCredentials(oauthParameters, new OAuthHmacSha1Signer());

// Retrieve user's list of Google Docs
String user = "any.user@anydomain.com";
URL feedUrl = new URL("https://docs.google.com/feeds/default/private/full" +
                      "?xoauth_requestor_id=" + user);

DocumentListFeed resultFeed = client.getFeed(feedUrl, DocumentListFeed.class);
for (DocumentListEntry entry : resultFeed.getEntries()) {
  System.out.println(entry.getTitle().getPlainText());
}

PHP

require_once 'Zend/Oauth/Consumer.php';
require_once 'Zend/Gdata/Docs.php';

$CONSUMER_KEY = 'example.com';
$CONSUMER_SECRET = 'abc123doremi';
$USER = 'any.user@anydomain.com';

$oauthOptions = array(
    'requestScheme' => Zend_Oauth::REQUEST_SCHEME_HEADER,
    'version' => '1.0',
    'signatureMethod' => 'HMAC-SHA1',
    'consumerKey' => $CONSUMER_KEY,
    'consumerSecret' => $CONSUMER_SECRET
);

$consumer = new Zend_Oauth_Consumer($oauthOptions);
$token = new Zend_Oauth_Token_Access();
$httpClient = $token->getHttpClient($oauthOptions);

$client = new Zend_Gdata_Docs($httpClient);

// Retrieve user's list of Google Docs
$feed = $client->getDocumentListFeed('https://docs.google.com/feeds/default/private/full?xoauth_requestor_id=' . urlencode($USER));
foreach ($feed->entries as $entry) {
  echo "$entry->title\n";
}

Python

Se utilizzi le classi v2.0+ più recenti basate su GDClient, utilizza:

import gdata.gauth
import gdata.docs.client

CONSUMER_KEY = 'example.com'
CONSUMER_SECRET = 'abc123doremi'
requestor_id = 'any.user@anydomain.com'

client = gdata.docs.client.DocsClient(source='yourCompany-YourAppName-v1')
client.auth_token = gdata.gauth.TwoLeggedOAuthHmacToken(
    CONSUMER_KEY, CONSUMER_SECRET, requestor_id)

# Retrieve user's list of Google Docs
feed = client.GetDocList()
for entry in feed.entry:
  print entry.title.text

Se utilizzi le classi v1.0 precedenti basate su GDataService, utilizza:

import gdata.auth
import gdata.docs.service

CONSUMER_KEY = 'example.com'
CONSUMER_SECRET = 'abc123doremi'
SIG_METHOD = gdata.auth.OAuthSignatureMethod.HMAC_SHA1

requestor_id = 'any.user@anydomain.com'

client = gdata.docs.service.DocsService(source='yourCompany-YourAppName-v1')
client.SetOAuthInputParameters(SIG_METHOD, CONSUMER_KEY, consumer_secret=CONSUMER_SECRET,
                               two_legged_oauth=True, requestor_id=requestor_id)

# Retrieve user's list of Google Docs
feed = client.GetDocumentListFeed()
for entry in feed.entry:
  print entry.title.text

# Change to another user on your domain
client.GetOAuthInputParameters().requestor_id = 'another.user@example.com'

.NET

using Google.GData.Client;
using Google.GData.Documents;

// Create an OAuth factory to use
GOAuthRequestFactory requestFactory = new GOAuthRequestFactory("writely", "yourCompany-YourAppName-v1");
requestFactory.ConsumerKey = "example.com";
requestFactory.ConsumerSecret = "abc123doremi";

String user = "any.user@anydomain.com";

DocumentsService client = new DocumentsService("yourCompany-YourAppName-v1");
client.RequestFactory = requestFactory;

// Retrieve user's list of Google Docs
DocumentsListQuery query = new DocumentsListQuery();
query.Uri = new OAuthUri("https://docs.google.com/feeds/default/private/full", user, requestFactory.ConsumerKey);

DocumentsFeed feed = client.Query(query);

foreach (DocumentEntry entry in feed.Entries)
{
  Console.WriteLine(entry.Title.Text);
}

Risorse ed esempi aggiuntivi di OAuth a due vie

Generazione di una chiave privata e di un certificato pubblico autofirmati

La chiave privata viene utilizzata per generare una firma, che deve essere inclusa in ogni richiesta. La chiave pubblica incorporata nel certificato viene utilizzata da Google per verificare la firma. La chiave pubblica deve essere una chiave RSA a 1024 bit codificata in un certificato X.509 in formato PEM. Il certificato deve essere inviato a Google al momento della registrazione.

Le sezioni seguenti forniscono esempi di come generare chiavi e certificati utilizzando due strumenti particolari: l'utilità OpenSSL e l'utilità keytool di Java.

Questi esempi non sono specifici delle API Google Data; puoi utilizzare le stesse utilità per generare chiavi per qualsiasi scopo.

Gli esempi presuppongono che la tua azienda si chiami My_Company e si trovi a Mountain View, in California, Stati Uniti, con il nome di dominio example.com.

Generazione di chiavi utilizzando OpenSSL

Per creare una coppia di chiavi RSA e il certificato corrispondente, puoi utilizzare il seguente comando:

# Generate the RSA keys and certificate
openssl req -x509 -nodes -days 365 -newkey rsa:1024 -sha1 -subj \
  '/C=US/ST=CA/L=Mountain View/CN=www.example.com' -keyout \
  myrsakey.pem -out /tmp/myrsacert.pem

Avviso: l'inclusione del parametro -nodes crea una chiave privata senza password per proteggerla. Tuttavia, ti consigliamo di omettere questo parametro per una maggiore sicurezza.

Il parametro -sha1 specifica che la chiave verrà utilizzata per generare firme SHA1.

Il parametro -subj specifica l'identità dell'applicazione rappresentata dal certificato.

Il parametro -keyout specifica il file che conterrà le chiavi. Questo file contiene informazioni sensibili e deve essere protetto e non condiviso con nessuno.

Il parametro -out specifica il file che conterrà il certificato in formato PEM (che può essere inviato a Google durante la registrazione).

Generare chiavi per il client .NET

Il framework .NET non riconosce le chiavi o i certificati archiviati in formato PEM. Pertanto, una volta creato il file .pem, è necessario un passaggio aggiuntivo:

openssl pkcs12 -export -in test_cert.pem -inkey myrsacert.pem -out myrsacert.pfx -name "Testing Certificate"

Questo passaggio genera un file PFX dalla chiave privata e dal certificato. Questo file può essere importato nella libreria client .NET per firmare digitalmente le richieste effettuate alle API di Google Data.

Generazione di chiavi per il client Java

Il client Java accetta le chiavi private nel formato PKCS#8. Dopo aver generato una chiave/un certificato utilizzando le istruzioni riportate sopra, crea un file .pk8 dal file .pem generato:

openssl pkcs8 -in myrsakey.pem -topk8 -nocrypt -out myrsakey.pk8

In alternativa, puoi utilizzare il keystore Java e l'utilità keytool per creare una coppia di chiavi RSA e il certificato corrispondente. Utilizza il seguente comando:

# Generate the RSA keys and certificate
keytool -genkey -v -alias Example -keystore ./Example.jks\
  -keyalg RSA -sigalg SHA1withRSA\
  -dname "CN=www.example.com, OU=Engineering, O=My_Company, L=Mountain  View, ST=CA, C=US"\
  -storepass changeme -keypass changeme

Avviso: "changeme" non è una password sicura, è solo un esempio.

Il parametro -dname specifica l'identità dell'applicazione rappresentata dal certificato. Il parametro -storepass specifica la password per proteggere il keystore. Il parametro -keypass specifica la password per proteggere la chiave privata.

Per scrivere il certificato in un file che può essere utilizzato nello strumento ManageDomains, utilizza questo comando:

# Output the public certificate to a file
keytool -export -rfc -keystore ./Example.jks -storepass changeme \
  -alias Example -file mycert.pem

Torna all'inizio