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.
Importante: non utilizzare ClientLogin per le nuove applicazioni. Utilizza invece il protocollo di autenticazione OAuth, più sicuro. ClientLogin è un protocollo di autenticazione deprecato e verrà ritirato il 20 aprile 2015. Da quel momento, le richieste ClientLogin non riceveranno più risposta. Se hai applicazioni esistenti che utilizzano ClientLogin, ti consigliamo di eseguire la migrazione a OAuth. Il supporto di ClientLogin in questa libreria verrà rimosso nella prossima release principale.
Questo documento descrive come utilizzare l'autenticazione per le applicazioni installate di Google all'interno di ciascuna delle librerie client delle API di Google Data.
Le applicazioni installate che devono accedere ai dati privati di un utente (protetti da un account Google o G Suite) possono utilizzare ClientLogin come mezzo programmatico per autenticare gli utenti. Un'applicazione installata è un'applicazione installata su un dispositivo, ad esempio un computer o un cellulare, anziché un'applicazione web.
Stai creando un'applicazione web?
Sconsigliamo alle applicazioni web di utilizzare ClientLogin come metodo di autenticazione. Consulta invece la sezione Utilizzo di AuthSub con le librerie client dell'API Google Data.
Pubblico
Questo documento è destinato agli sviluppatori che vogliono scrivere applicazioni che accedono a un servizio Google Data utilizzando le librerie client delle API Google Data. Questo documento presuppone che tu abbia familiarità con l'interfaccia ClientLogin. Per una descrizione completa del protocollo ClientLogin, consulta Autenticazione per applicazioni installate.
Le librerie client delle API di dati di Google forniscono metodi per aiutarti a utilizzare ClientLogin nelle tue applicazioni. In particolare, esistono metodi per acquisire un token di autenticazione, gestire le sfide CAPTCHA, richiamare il token di autenticazione per un utilizzo successivo e inviare l'intestazione Authorization corretta con ogni richiesta.
Utilizzo di ClientLogin e delle API di Google Data senza le librerie client
Le librerie client non sono l'unico modo per utilizzare ClientLogin nelle tue applicazioni. Tutto ciò che devi sapere è disponibile nella documentazione di ClientLogin, Autenticazione per le applicazioni installate. Tuttavia, le librerie client forniscono metodi utili per utilizzare ClientLogin nella tua applicazione Google Data.
Utilizzo di ClientLogin e delle API Google Data: esempi di librerie client
Questa sezione fornisce esempi di utilizzo delle librerie client delle API di dati di Google per seguire i passaggi descritti nella sezione "L'interfaccia ClientLogin" della documentazione di ClientLogin.
Gli esempi riportati in questo documento mostrano l'interazione con Google Calendar (anche se non è necessario conoscere l'API Calendar Data per seguirli).
Ottenere un token di autorizzazione
Per utilizzare ClientLogin, la tua applicazione deve effettuare una richiesta HTTPS POST al gestore ClientLogin https://www.google.com/accounts/ClientLogin. Il corpo di POST deve essere strutturato
come un post del modulo con la codifica predefinita application/x-www-form-urlencoded. Utilizzando una delle librerie client, puoi effettuare questa richiesta con una sola riga di codice.
I seguenti esempi configurano prima un oggetto servizio che si connette all'API Calendar Data, quindi effettuano una richiesta HTTP POST
al gestore ClientLogin.
Java
import com.google.gdata.client.*; import com.google.gdata.client.calendar.*; CalendarService client = new CalendarService("yourCompany-yourAppName-v1"); client.setUserCredentials("user@example.com", "pa$$word");
If you know your users will be using a G Suite account (as opposed to a Google/Gmail Account), you can streamline the login process by specifying the appropriate ClientLogin account type:
import com.google.gdata.client.*; import com.google.gdata.client.calendar.*; CalendarService client = new CalendarService("yourCompany-yourAppName-v1"); client.setUserCredentials("user@example.com", "pa$$word", ClientLoginAccountType.HOSTED);
.NET
using Google.GData.Client; using Google.GData.Calendar; CalendarService client = new CalendarService("yourCompany-yourAppName-v1"); client.setUserCredentials("user@example.com", "pa$$word"); client.QueryAuthenticationToken(); // Authenticate the user immediately
If you know your users will be using a G Suite account (as opposed to a Google/Gmail Account), you can streamline the login process by specifying the appropriate ClientLogin account type:
using Google.GData.Client; using Google.GData.Calendar; GDataGAuthRequestFactory authFactory = new GDataGAuthRequestFactory("cl", "yourCompany-yourAppName-v1"); authFactory.AccountType = "HOSTED"; CalendarService client = new CalendarService(authFactory.ApplicationName); client.RequestFactory = authFactory; client.setUserCredentials("user@example.com", "pa$$word"); client.QueryAuthenticationToken(); // Authenticate the user immediately
PHP
require_once 'Zend/Loader.php'; Zend_Loader::loadClass('Zend_Gdata_ClientLogin'); Zend_Loader::loadClass('Zend_Gdata_Calendar'); $serviceName = Zend_Gdata_Calendar::AUTH_SERVICE_NAME; // predefined service name ('cl') for calendar $applicationName = 'yourCompany-yourAppName-v1'; // Create an authenticated HTTP client $httpClient = Zend_Gdata_ClientLogin::getHttpClient('user@example.com', 'pa$$word', $serviceName, null, $applicationName); $client = new Zend_Gdata_Calendar($httpClient, $applicationName); // Create an instance of the Calendar service
If you know your users will be using a G Suite account (as opposed to a Google/Gmail Account), you can streamline the login process by specifying the appropriate ClientLogin account type:
require_once 'Zend/Loader.php'; Zend_Loader::loadClass('Zend_Gdata_ClientLogin'); Zend_Loader::loadClass('Zend_Gdata_Calendar'); $serviceName = Zend_Gdata_Calendar::AUTH_SERVICE_NAME; $applicationName = 'yourCompany-yourAppName-v1'; $accountType = 'HOSTED'; $httpClient = Zend_Gdata_ClientLogin::getHttpClient( 'user@example.com', 'pa$$word', $serviceName, null, $applicationName, null, null, null, $accountType); $client = new Zend_Gdata_Calendar($httpClient, $applicationName);
Python
Se utilizzi le classi v2.0+ più recenti basate su GDClient, utilizza:
import gdata.calendar.client email = 'user@example.com' password = 'pa$$word' application_name = 'yourCompany-yourAppName-v1' client = gdata.calendar.client.CalendarClient() auth_token = client.ClientLogin(email, password, application_name, service='cl')
If you know your users will be using a G Suite account (as opposed to a Google/Gmail Account), you can streamline the login process by specifying the appropriate ClientLogin account type:
auth_token = client.ClientLogin(email, password, application_name, account_type='HOSTED', service='cl')
Alternatively, if you're using the older v1.0 classes based off of GDataService, the calls are a bit different:
import gdata.calendar.service email = 'user@example.com' password = 'pa$$word' application_name = 'yourCompany-yourAppName-v1' client = gdata.calendar.service.CalendarService() client.ClientLogin(email, password, source=application_name) # OR, you can use ProgrammaticLogin() client = gdata.calendar.service.CalendarService(email=email, password=password, source=application_name) client.ProgrammaticLogin()
Come nella versione 2.0 e successive, se gli utenti utilizzeranno un account G Suite, puoi specificare il tipo di account ClientLogin appropriato:
import gdata.calendar.service client = gdata.calendar.service.CalendarService() client.ClientLogin('user@example.com', 'pa$$word', account_type='HOSTED', source='yourCompany-yourAppName-v1')
See the request parameters section for a
detailed explanation of each ClientLogin parameter. A complete list of available service names is available in the FAQ.
Note: By default, the client libraries set an account-type parameter to
HOSTED_OR_GOOGLE. That means ClientLogin will first try to authenticate the user's credentials as a G Suite account. If that fails,
it will try to authenticate as a Google Account. This becomes tricky if user@example.com is both a Google Account and a G Suite account.
In that special case, set the account type to GOOGLE if the user wishes to use the Google Accounts version of user@example.com.
Once the login information has been successfully authenticated, Google returns a token, which your application will reference each time
it requests access to the user's account, such as to GET or POST data. The token remains valid for a set length of time,
defined by whichever Google service you're working with. Typically, tokens remain valid for 2 weeks.
Recalling an auth token
After your application has authenticated the user once, there's no need for them to input their credentials again.
We recommend storing the Auth token in your database and recalling it as necessary. That will save the overhead of an additional
HTTPS POST and a possible CAPTCHA challenge.
The libraries provide getters/setters for accessing the token:
Java
String token = '12345abcde'; // TODO: Read user's token from your database client.setUserToken(token); UserToken auth_token = (UserToken) client.getAuthTokenFactory().getAuthToken(); token = auth_token.getValue(); // token is '12345abcde'
.NET
String token = '12345abcde'; // TODO: Read user's token from your database client.SetAuthenticationToken(token); GDataGAuthRequestFactory requestFactory = (GDataGAuthRequestFactory) client.RequestFactory; token = requestFactory.GAuthToken; // token is '12345abcde'
PHP
$token = '12345abcde'; // TODO: Read user's token from your database $client->getHttpClient()->setClientLoginToken($token); $token = $client->getHttpClient()->getClientLoginToken(); // $token is '12345abcde'
Python
If you're using the newer v2.0+ classes based off of GDClient, use:
import gdata.gauth token = '12345abcde' # TODO: Read user's token from your database client.auth_token = gdata.gauth.ClientLoginToken(token) token = client.auth_token.token_string # token is '12345abcde'
If you're using the older v1.0 classes based off of GDataService, the process is a bit different.
token = '12345abcde' # TODO: Read user's token from your database client.SetClientLoginToken(token) token = client.GetClientLoginToken() # token is '12345abcde'
Handling CAPTCHA challenges
A failure response from ClientLogin contains an error code and a URL to an error page that can be displayed to the user. If the error code is a CAPTCHA challenge, the response also includes a URL to a CAPTCHA image and a special token. Your application should be able to solicit an answer from the user and then retry the login request.
Java
String email = "user@example.com"; String password = "pa$$word"; try { client.setUserCredentials(email, password); } catch (CaptchaRequiredException e) { System.out.println("Please visit " + e.getCaptchaUrl()); System.out.print("Answer to the challenge? "); BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); String answer = in.readLine(); service.setUserCredentials(email, password, e.getCaptchaToken(), answer); } catch (AuthenticationException e) { System.out.println(e.getMessage()); }
.NET
try { client.setUserCredentials("user@example.com", "pa$$word"); client.QueryAuthenticationToken(); // Authenticate the user immediately } catch (CaptchaRequiredException e) { Console.WriteLine("Please visit " + e.Url); Console.Write("Answer to the challenge? "); String answer = Console.ReadLine(); GDataGAuthRequestFactory requestFactory = (GDataGAuthRequestFactory) client.RequestFactory; requestFactory.CaptchaAnswer = answer; requestFactory.CaptchaToken = e.Token; client.QueryAuthenticationToken(); // authenticate the user again } catch (InvalidCredentialsException e) { Console.WriteLine(e.Message); } catch (AuthenticationException e) { Console.WriteLine(e.Message); }
PHP
$email = 'user@example.com'; $password = 'pa$$word'; $serviceName = 'cl'; // 'cl' is the service name for the Calendar API $appName = 'yourCompany-yourAppName-v1'; try { $httpClient = Zend_Gdata_ClientLogin::getHttpClient($email, $password, $serviceName, null, $appName); } catch (Zend_Gdata_App_CaptchaRequiredException $e) { echo '<a href="' . $e->getCaptchaUrl() . '">CAPTCHA answer required to login</a>'; $answer = 'Your answer to the challenge'; $httpClient = Zend_Gdata_ClientLogin::getHttpClient( $email, $password, $serviceName, null, $appName, $e->getCaptchaToken(), $answer); } catch (Zend_Gdata_App_AuthException $e) { echo 'Error: ' . $e->getMessage(); if ($e->getResponse() != null) { echo 'Body: ' . $e->getResponse()->getBody(); } }
Python
Se utilizzi le classi v2.0+ più recenti basate su GDClient, utilizza:
import gdata.client try: client.ClientLogin(email, password, application_name, service='cl') except gdata.client.CaptchaChallenge as challenge: print 'Please visit ' + challenge.captcha_url answer = raw_input('Answer to the challenge? ') client.ClientLogin(email, password, application_name, captcha_token=challenge.captcha_token, captcha_response=answer) except gdata.client.BadAuthentication: exit('Users credentials were unrecognized') except gdata.client.RequestError: exit('Login Error')
Se utilizzi le classi v1.0 precedenti basate su GDataService, la procedura è leggermente diversa.
import gdata.service email = 'user@example.com' password = 'pa$$word' application_name = 'yourCompany-yourAppName-v1' try: client.ClientLogin(email, password, source=application_name) except gdata.service.CaptchaRequired: print 'Please visit ' + client.captcha_url answer = raw_input('Answer to the challenge? ') client.ClientLogin(email, password, source=application_name, captcha_token=client.captcha_token, captcha_response=answer) except gdata.service.BadAuthentication: exit('Users credentials were unrecognized') except gdata.service.Error: exit('Login Error')
Per ulteriori informazioni sui CAPTCHA, consulta la sezione Risposta ClientLogin della documentazione "Autenticazione per applicazioni installate".
Risorse aggiuntive ed esempi
- Esempi di ClientLogin nel blog Google Data API Tips
- Autenticazione per le applicazioni installate