ClientLogin in den Google Data Protocol-Clientbibliotheken

Warnung: Auf dieser Seite geht es um die älteren APIs von Google, die Google Data APIs. Sie ist nur für die APIs relevant, die im Google Data APIs-Verzeichnis aufgeführt sind. Viele davon wurden durch neuere APIs ersetzt. Informationen zu einer bestimmten neuen API finden Sie in der Dokumentation der jeweiligen API. Informationen zum Autorisieren von Anfragen mit einer neueren API finden Sie unter Authentifizierung und Autorisierung von Google-Konten.

Wichtig: Verwenden Sie ClientLogin nicht für neue Anwendungen. Verwenden Sie stattdessen das sicherere OAuth-Authentifizierungsprotokoll. ClientLogin ist ein eingestelltes Authentifizierungsprotokoll, das am 20. April 2015 eingestellt wird. Ab diesem Zeitpunkt werden ClientLogin-Anfragen nicht mehr beantwortet. Wenn Sie Anwendungen verwenden, die ClientLogin nutzen, empfehlen wir Ihnen, zu OAuth zu migrieren. Die ClientLogin-Unterstützung in dieser Bibliothek wird in der nächsten Hauptversion entfernt.

In diesem Dokument wird beschrieben, wie Sie die Authentifizierung für installierte Anwendungen von Google in den einzelnen Google Data API-Clientbibliotheken verwenden.

Installierte Anwendungen, die auf die privaten Daten eines Nutzers zugreifen müssen, die durch ein Google- oder G Suite-Konto geschützt sind, können ClientLogin als programmatische Methode zur Authentifizierung von Nutzern verwenden. Eine „installierte Anwendung“ ist eine Anwendung, die auf einem Gerät wie einem Computer oder einem Mobiltelefon installiert ist, im Gegensatz zu einer Webanwendung.

Erstellen Sie eine Webanwendung?

Es wird davon abgeraten, ClientLogin als Authentifizierungsmethode für Webanwendungen zu verwenden. Weitere Informationen finden Sie unter AuthSub mit den Google Data API-Clientbibliotheken verwenden.

Zielgruppe

Dieses Dokument richtet sich an Entwickler, die Anwendungen schreiben möchten, die mit den Google Data APIs-Clientbibliotheken auf einen Google Data-Dienst zugreifen. In diesem Dokument wird davon ausgegangen, dass Sie mit der ClientLogin-Schnittstelle vertraut sind. Eine vollständige Beschreibung des ClientLogin-Protokolls finden Sie unter Authentifizierung für installierte Anwendungen.

Die Google Data API-Clientbibliotheken bieten Methoden, mit denen Sie ClientLogin in Ihren Anwendungen verwenden können. Es gibt Methoden zum Abrufen eines Authentifizierungstokens, zum Verarbeiten von CAPTCHA-Abfragen, zum Abrufen des Authentifizierungstokens für die spätere Verwendung und zum Senden des richtigen Authorization-Headers mit jeder Anfrage.

ClientLogin und Google Data APIs ohne Clientbibliotheken verwenden

Die Clientbibliotheken sind keineswegs die einzige Möglichkeit, ClientLogin in Ihren Anwendungen zu verwenden. Alles Wissenswerte finden Sie in der ClientLogin-Dokumentation unter Authentifizierung für installierte Anwendungen. Die Clientbibliotheken bieten jedoch hilfreiche Methoden für die Verwendung von ClientLogin in Ihrer Google Data-Anwendung.

Mit ClientLogin und den Google Data APIs arbeiten: Beispiele für Clientbibliotheken

In diesem Abschnitt finden Sie Beispiele für die Verwendung der Google Data APIs-Clientbibliotheken, um die Schritte aus dem Abschnitt Die ClientLogin-Schnittstelle der ClientLogin-Dokumentation auszuführen.

In den Beispielen in diesem Dokument wird die Interaktion mit Google Kalender veranschaulicht. Sie müssen jedoch nichts über die Calendar Data API wissen, um den Beispielen folgen zu können.

Auth-Token abrufen

Wenn Sie ClientLogin verwenden möchten, muss Ihre Anwendung eine HTTPS-POST an den Handler https://www.google.com/accounts/ClientLogin des ClientLogin-Handlers senden. Der POST-Body sollte als Formularbeitrag mit der Standardcodierung application/x-www-form-urlencoded strukturiert sein. Mit einer der Clientbibliotheken können Sie diese Anfrage in einer einzigen Zeile Code stellen.

In den folgenden Beispielen wird zuerst ein Dienstobjekt eingerichtet, das eine Verbindung zur Calendar Data API herstellt, und dann wird ein HTTP-POST an den ClientLogin-Handler gesendet.

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

Wenn Sie die neueren Klassen ab Version 2.0 verwenden, die auf GDClient basieren, verwenden Sie:

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

Wie in Version 2.0 und höher können Sie den entsprechenden ClientLogin-Kontotyp angeben, wenn Ihre Nutzer ein G Suite-Konto verwenden:

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

Wenn Sie die neueren Klassen ab Version 2.0 verwenden, die auf GDClient basieren, verwenden Sie:

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

Wenn Sie die älteren v1.0-Klassen auf Grundlage von GDataService verwenden, ist der Vorgang etwas anders.

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

Weitere Informationen zu CAPTCHAs finden Sie in der Dokumentation „Authentifizierung für installierte Anwendungen“ im Abschnitt ClientLogin-Antwort.

Zusätzliche Ressourcen und Beispiele

Nach oben