Cảnh báo: Trang này nói về các API cũ hơn của Google, tức là Google Data API; trang này chỉ liên quan đến những API có trong thư mục Google Data API. Nhiều API trong số đó đã được thay thế bằng các API mới hơn. Để biết thông tin về một API mới cụ thể, hãy xem tài liệu về API mới đó. Để biết thông tin về cách uỷ quyền cho các yêu cầu bằng một API mới hơn, hãy xem phần Xác thực và uỷ quyền Tài khoản Google.
Quan trọng: Không sử dụng ClientLogin cho các ứng dụng mới. Thay vào đó, hãy sử dụng giao thức xác thực OAuth an toàn hơn. ClientLogin là một giao thức xác thực không được dùng nữa và sẽ ngừng hoạt động vào ngày 20 tháng 4 năm 2015. Vào thời điểm đó, các yêu cầu ClientLogin sẽ không được trả lời nữa. Nếu có các ứng dụng hiện tại sử dụng ClientLogin, bạn nên di chuyển sang OAuth. Chế độ hỗ trợ ClientLogin trong thư viện này sẽ bị xoá trong bản phát hành chính tiếp theo.
Tài liệu này mô tả cách sử dụng tính năng Xác thực cho các ứng dụng đã cài đặt của Google trong từng thư viện ứng dụng Google Data API.
Các ứng dụng đã cài đặt cần truy cập vào dữ liệu riêng tư của người dùng (được bảo vệ bằng Tài khoản Google hoặc tài khoản G Suite) có thể sử dụng ClientLogin làm phương tiện theo chương trình để xác thực người dùng. "Ứng dụng đã cài đặt" là ứng dụng được cài đặt trên một thiết bị, chẳng hạn như máy tính hoặc điện thoại di động, thay vì ứng dụng web.
Bạn đang tạo một ứng dụng web?
Các ứng dụng web không nên sử dụng ClientLogin làm phương thức xác thực. Thay vào đó, vui lòng xem phần Sử dụng AuthSub với Thư viện ứng dụng Google Data API.
Đối tượng
Tài liệu này dành cho những nhà phát triển muốn viết các ứng dụng truy cập vào một dịch vụ Dữ liệu của Google bằng thư viện ứng dụng API Dữ liệu của Google. Tài liệu này giả định rằng bạn đã quen thuộc với giao diện ClientLogin. Để xem nội dung mô tả đầy đủ về giao thức ClientLogin, hãy xem phần Xác thực cho các ứng dụng đã cài đặt.
Thư viện ứng dụng Google Data API cung cấp các phương thức giúp bạn sử dụng ClientLogin trong các ứng dụng của mình. Cụ thể, có các phương thức để lấy mã thông báo xác thực, xử lý thử thách CAPTCHA, thu hồi mã thông báo xác thực để sử dụng sau này và gửi tiêu đề Authorization chính xác với mọi yêu cầu.
Sử dụng ClientLogin và Google Data API mà không cần thư viện ứng dụng
Thư viện ứng dụng không phải là cách duy nhất để sử dụng ClientLogin trong các ứng dụng của bạn. Bạn có thể tìm thấy mọi thông tin cần biết trong tài liệu ClientLogin, Xác thực cho các ứng dụng đã cài đặt. Tuy nhiên, các thư viện ứng dụng cung cấp những phương thức hữu ích để sử dụng ClientLogin trong ứng dụng Google Data.
Làm việc với ClientLogin và Google Data API: ví dụ về thư viện ứng dụng
Phần này đưa ra ví dụ về cách sử dụng thư viện ứng dụng Google Data APIs để làm theo các bước nêu trong phần "Giao diện ClientLogin" của tài liệu ClientLogin.
Các ví dụ trong tài liệu này minh hoạ cách tương tác với Lịch Google (mặc dù bạn không cần biết bất kỳ thông tin nào về Calendar Data API để làm theo các ví dụ).
Lấy mã xác thực
Để sử dụng ClientLogin, ứng dụng của bạn phải tạo một POST HTTPS cho trình xử lý của ClientLogin https://www.google.com/accounts/ClientLogin. Nội dung POST phải được cấu trúc dưới dạng một biểu mẫu đăng với chế độ mã hoá mặc định application/x-www-form-urlencoded. Khi sử dụng một trong các thư viện ứng dụng, bạn có thể đưa ra yêu cầu này chỉ bằng một dòng mã.
Các mẫu sau đây trước tiên thiết lập một đối tượng dịch vụ kết nối với Calendar Data API, sau đó tạo một HTTP POST cho trình xử lý 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
Nếu bạn đang sử dụng các lớp v2.0+ mới hơn dựa trên GDClient, hãy sử dụng:
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()
Như trong phiên bản 2.0 trở lên, nếu người dùng sẽ sử dụng tài khoản G Suite, bạn có thể chỉ định loại tài khoản ClientLogin thích hợp:
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
Nếu bạn đang sử dụng các lớp v2.0+ mới hơn dựa trên GDClient, hãy sử dụng:
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')
Nếu bạn đang sử dụng các lớp v1.0 cũ dựa trên GDataService, thì quy trình này sẽ hơi khác.
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')
Để biết thêm thông tin về CAPTCHA, hãy xem phần Phản hồi ClientLogin trong tài liệu "Xác thực cho các ứng dụng đã cài đặt".
Tài nguyên và mẫu khác
- Ví dụ về ClientLogin trên Google Data API Tips Blog
- Xác thực cho các ứng dụng đã cài đặt