Google 데이터 프로토콜 클라이언트 라이브러리의 ClientLogin

경고: 이 페이지는 Google의 이전 API인 Google Data API에 관한 것으로, Google Data API 디렉터리에 표시된 API 중 상당수가 최신 API로 대체된 API입니다. 특정 새 API에 대한 자세한 내용은 새 API 문서를 참조하세요. 최신 API를 사용하여 요청을 승인하는 방법은 Google 계정 인증 및 승인을 참고하세요.

중요: 새 애플리케이션에 ClientLogin을 사용하지 마세요. 대신 더 안전한 OAuth 인증 프로토콜을 사용하세요. ClientLogin은 지원 중단된 인증 프로토콜로, 2015년 4월 20일에 사용이 중단되었습니다. 그렇게 되면 ClientLogin 요청에 더 이상 응답하지 않습니다. ClientLogin을 사용하는 기존 애플리케이션이 있는 경우 OAuth로 이전하는 것이 좋습니다. 이 라이브러리의 ClientLogin 지원은 다음 주요 버전에서 삭제될 예정입니다.

이 문서에서는 각 Google Data API 클라이언트 라이브러리 내에서 Google의 설치된 애플리케이션에 대한 인증을 사용하는 방법을 설명합니다.

설치된 애플리케이션 (Google 또는 G Suite 계정으로 보호되는 사용자의 비공개 데이터에 액세스해야 함)은 클라이언트 로그인을 프로그래매틱 방식으로 사용하여 사용자를 인증할 수 있습니다. '설치된 애플리케이션'은 웹 애플리케이션이 아닌 데스크톱 컴퓨터 또는 휴대전화와 같은 기기에 설치된 애플리케이션입니다.

웹 애플리케이션을 빌드하시나요?

웹 애플리케이션에서 인증 방법으로 ClientLogin을 사용하지 않는 것이 좋습니다. 대신 Google Data API 클라이언트 라이브러리에 AuthSub 사용을 참조하세요.

대상

이 문서는 Google Data API 클라이언트 라이브러리를 사용하여 Google 데이터 서비스에 액세스하는 애플리케이션을 작성하려는 개발자를 대상으로 합니다. 이 문서에서는 ClientLogin 인터페이스에 익숙하다고 가정합니다. ClientLogin의 프로토콜에 대한 자세한 설명은 설치된 애플리케이션 인증을 참조하세요.

Google Data API 클라이언트 라이브러리는 애플리케이션에서 ClientLogin을 사용하는 데 도움이 되는 메서드를 제공합니다. 특히 인증 토큰을 획득하고, 보안문자 문제를 처리하고, 나중에 사용할 수 있도록 인증 토큰을 리콜하고, 모든 요청에 올바른 Authorization 헤더를 전송하는 메서드가 있습니다.

클라이언트 라이브러리 없이 ClientLogin 및 Google Data API 사용

클라이언트 라이브러리가 애플리케이션에서 ClientLogin을 사용하는 유일한 방법은 아닙니다. ClientLogin 문서, 설치된 애플리케이션 인증에서 필요한 모든 정보를 확인할 수 있습니다. 하지만 클라이언트 라이브러리는 Google 데이터 애플리케이션에서 ClientLogin을 활용하는 데 유용한 방법을 제공합니다.

ClientLogin 및 Google Data API 작업: 클라이언트 라이브러리 예

이 섹션에서는 Google 데이터 API 클라이언트 라이브러리를 사용하여 ClientLogin 문서의 'ClientLogin 인터페이스' 섹션에 설명된 단계를 따릅니다.

이 문서의 모든 예는 Google Calendar와 상호작용하는 방법을 보여주며, 예제를 따르기 위해 Calendar Data API에 대해 몰라도 됩니다.

인증 토큰 가져오기

ClientLogin을 사용하려면 애플리케이션이 ClientLogin의 핸들러 https://www.google.com/accounts/ClientLogin에 HTTPS POST를 만들어야 합니다. POST 본문은 기본 인코딩 application/x-www-form-urlencoded를 사용하는 양식 게시물로 구성해야 합니다. 클라이언트 라이브러리 중 하나를 사용하여 코드 한 줄로 이 요청을 할 수 있습니다.

다음 샘플에서는 먼저 Calendar Data API에 연결하는 서비스 객체를 설정한 후 HTTP POST를 ClientLogin 핸들러에 만듭니다.

자바

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

GDClient를 기반으로 하는 최신 v2.0 이상 클래스를 사용하는 경우 다음을 사용합니다.

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

v2.0 이상과 마찬가지로 사용자가 G Suite 계정을 사용하는 경우 적절한 ClientLogin 계정 유형을 지정할 수 있습니다.

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

GDClient를 기반으로 하는 최신 v2.0 이상 클래스를 사용하는 경우 다음을 사용합니다.

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

GDataService에 기반한 이전 v1.0 클래스를 사용하는 경우 프로세스가 약간 다릅니다.

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

보안문자에 대한 자세한 내용은 '설치된 애플리케이션 인증' 문서의 ClientLogin 응답 섹션을 참조하세요.

추가 리소스 및 샘플

맨 위로