ClientLogin nas bibliotecas de cliente do protocolo de dados do Google

Aviso: esta página é sobre as APIs mais antigas do Google, as APIs de dados do Google. Relevante apenas para as APIs listadas no diretório das APIs de dados do Google, muitas delas foram substituídas por APIs mais recentes. Para mais informações sobre uma nova API específica, consulte a documentação da nova API. Para informações sobre autorização de solicitações com uma API mais recente, consulte Autenticação e autorização de Contas do Google.

Importante: não use ClientLogin para novos aplicativos. Em vez disso, use o protocolo de autenticação OAuth mais seguro. O ClientLogin é um protocolo de autenticação descontinuado e será desativado em 20 de abril de 2015. A partir dessa data, as solicitações do ClientLogin não serão mais respondidas. Se você tiver aplicativos que usam ClientLogin, recomendamos migrar para o OAuth. O suporte a ClientLogin nesta biblioteca será removido na próxima versão principal.

Este documento descreve como usar a Autenticação para aplicativos instalados do Google em cada uma das bibliotecas de cliente da API Google Data.

Os aplicativos instalados que precisam acessar os dados particulares de um usuário (protegidos por uma conta do Google ou do G Suite) podem usar o ClientLogin como meios programáticos para autenticar usuários. Um "aplicativo instalado" é aquele instalado em um dispositivo, como um computador ou smartphone, em oposição a um aplicativo da Web.

Você está criando um aplicativo da Web?

Não é recomendável que os aplicativos da Web usem ClientLogin como método de autenticação. Em vez disso, consulte Como usar o tmp com as bibliotecas de cliente da API Google Data.

Público-alvo

Este documento é para os desenvolvedores criarem aplicativos que acessam um serviço de dados do Google usando as bibliotecas de cliente das APIs de dados do Google. Para usar este documento, é necessário ter familiaridade com a interface do ClientLogin. Para uma descrição completa do protocolo do ClientLogin, consulte Autenticação para aplicativos instalados.

As bibliotecas de cliente da API Google Data fornecem métodos para ajudar você a usar o ClientLogin nos seus aplicativos. Especificamente, há métodos para adquirir um token de autenticação, lidando com desafios do CAPTCHA, recuperando o token de autenticação para uso posterior e enviando o cabeçalho Authorization correto com cada solicitação.

Uso de ClientLogin e APIs de dados do Google sem as bibliotecas do cliente

As bibliotecas de cliente não são a única maneira de usar o ClientLogin nos seus aplicativos. Encontre tudo o que você precisa saber na documentação do ClientLogin, Autenticação para aplicativos instalados. No entanto, as bibliotecas do cliente oferecem métodos úteis para utilizar o ClientLogin no seu aplicativo de dados do Google.

Como trabalhar com ClientLogin e as APIs de dados do Google: exemplos da biblioteca de cliente

Nesta seção, mostramos exemplos de como usar as bibliotecas de cliente das APIs de dados do Google para seguir as etapas descritas na seção Interface ClientLogin da documentação do ClientLogin.

Os exemplos ao longo deste documento demonstram a interação com o Google Agenda (embora você não precise saber nada sobre a API Data Data para seguir os exemplos).

Como conseguir um token de autenticação

Para usar o ClientLogin, seu aplicativo precisa criar um POST HTTPS para o gerenciador https://www.google.com/accounts/ClientLogin do ClientLogin. O corpo POST precisa ser estruturado como uma postagem de formulário com a codificação padrão application/x-www-form-urlencoded. Usando uma das bibliotecas de cliente, é possível fazer essa solicitação em uma única linha de código.

Os exemplos a seguir primeiro configuram um objeto de serviço que se conecta à API Calendar Data e depois criam um POST HTTP para o gerenciador 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 você estiver usando as classes mais recentes da v2.0 ou posterior com base no GDClient, use:

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

Como na v2.0+, se os usuários estiverem usando uma conta do G Suite, você poderá especificar o tipo de conta do ClientLogin apropriado:

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 você estiver usando as classes mais recentes da v2.0 ou posterior com base no GDClient, use:

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 você estiver usando as classes mais antigas da v1.0 com base em GDataService, o processo será um pouco diferente.

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

Para mais informações sobre CAPTCHAs, consulte a seção Resposta de login do cliente da documentação "Autenticação para aplicativos instalados".

Outros recursos e amostras

Voltar ao início