1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "google_apis/gaia/gaia_auth_fetcher.h"
11 #include "base/json/json_reader.h"
12 #include "base/json/json_writer.h"
13 #include "base/profiler/scoped_tracker.h"
14 #include "base/strings/string_split.h"
15 #include "base/strings/string_util.h"
16 #include "base/strings/stringprintf.h"
17 #include "base/values.h"
18 #include "google_apis/gaia/gaia_auth_consumer.h"
19 #include "google_apis/gaia/gaia_constants.h"
20 #include "google_apis/gaia/gaia_urls.h"
21 #include "google_apis/gaia/google_service_auth_error.h"
22 #include "net/base/escape.h"
23 #include "net/base/load_flags.h"
24 #include "net/http/http_response_headers.h"
25 #include "net/http/http_status_code.h"
26 #include "net/url_request/url_fetcher.h"
27 #include "net/url_request/url_request_context_getter.h"
28 #include "net/url_request/url_request_status.h"
31 const int kLoadFlagsIgnoreCookies
= net::LOAD_DO_NOT_SEND_COOKIES
|
32 net::LOAD_DO_NOT_SAVE_COOKIES
;
34 static bool CookiePartsContains(const std::vector
<std::string
>& parts
,
36 for (std::vector
<std::string
>::const_iterator it
= parts
.begin();
37 it
!= parts
.end(); ++it
) {
38 if (LowerCaseEqualsASCII(*it
, part
))
44 bool ExtractOAuth2TokenPairResponse(base::DictionaryValue
* dict
,
45 std::string
* refresh_token
,
46 std::string
* access_token
,
47 int* expires_in_secs
) {
48 DCHECK(refresh_token
);
50 DCHECK(expires_in_secs
);
52 if (!dict
->GetStringWithoutPathExpansion("refresh_token", refresh_token
) ||
53 !dict
->GetStringWithoutPathExpansion("access_token", access_token
) ||
54 !dict
->GetIntegerWithoutPathExpansion("expires_in", expires_in_secs
)) {
63 // TODO(chron): Add sourceless version of this formatter.
65 const char GaiaAuthFetcher::kClientLoginFormat
[] =
68 "PersistentCookie=%s&"
73 const char GaiaAuthFetcher::kClientLoginCaptchaFormat
[] =
76 "PersistentCookie=%s&"
83 const char GaiaAuthFetcher::kIssueAuthTokenFormat
[] =
89 const char GaiaAuthFetcher::kClientLoginToOAuth2BodyFormat
[] =
90 "scope=%s&client_id=%s";
92 const char GaiaAuthFetcher::kClientLoginToOAuth2WithDeviceTypeBodyFormat
[] =
93 "scope=%s&client_id=%s&device_type=chrome";
95 const char GaiaAuthFetcher::kOAuth2CodeToTokenPairBodyFormat
[] =
97 "grant_type=authorization_code&"
102 const char GaiaAuthFetcher::kOAuth2RevokeTokenBodyFormat
[] =
105 const char GaiaAuthFetcher::kGetUserInfoFormat
[] =
108 const char GaiaAuthFetcher::kMergeSessionFormat
[] =
113 const char GaiaAuthFetcher::kUberAuthTokenURLFormat
[] =
117 const char GaiaAuthFetcher::kOAuthLoginFormat
[] = "service=%s&source=%s";
120 const char GaiaAuthFetcher::kAccountDeletedError
[] = "AccountDeleted";
122 const char GaiaAuthFetcher::kAccountDisabledError
[] = "AccountDisabled";
124 const char GaiaAuthFetcher::kBadAuthenticationError
[] = "BadAuthentication";
126 const char GaiaAuthFetcher::kCaptchaError
[] = "CaptchaRequired";
128 const char GaiaAuthFetcher::kServiceUnavailableError
[] =
129 "ServiceUnavailable";
131 const char GaiaAuthFetcher::kErrorParam
[] = "Error";
133 const char GaiaAuthFetcher::kErrorUrlParam
[] = "Url";
135 const char GaiaAuthFetcher::kCaptchaUrlParam
[] = "CaptchaUrl";
137 const char GaiaAuthFetcher::kCaptchaTokenParam
[] = "CaptchaToken";
140 const char GaiaAuthFetcher::kCookiePersistence
[] = "true";
142 // TODO(johnnyg): When hosted accounts are supported by sync,
143 // we can always use "HOSTED_OR_GOOGLE"
144 const char GaiaAuthFetcher::kAccountTypeHostedOrGoogle
[] =
146 const char GaiaAuthFetcher::kAccountTypeGoogle
[] =
150 const char GaiaAuthFetcher::kSecondFactor
[] = "Info=InvalidSecondFactor";
152 const char GaiaAuthFetcher::kWebLoginRequired
[] = "Info=WebLoginRequired";
155 const char GaiaAuthFetcher::kAuthHeaderFormat
[] =
156 "Authorization: GoogleLogin auth=%s";
158 const char GaiaAuthFetcher::kOAuthHeaderFormat
[] = "Authorization: OAuth %s";
160 const char GaiaAuthFetcher::kOAuth2BearerHeaderFormat
[] =
161 "Authorization: Bearer %s";
163 const char GaiaAuthFetcher::kDeviceIdHeaderFormat
[] = "X-Device-ID: %s";
165 const char GaiaAuthFetcher::kClientLoginToOAuth2CookiePartSecure
[] = "secure";
167 const char GaiaAuthFetcher::kClientLoginToOAuth2CookiePartHttpOnly
[] =
170 const char GaiaAuthFetcher::kClientLoginToOAuth2CookiePartCodePrefix
[] =
173 const int GaiaAuthFetcher::kClientLoginToOAuth2CookiePartCodePrefixLength
=
174 arraysize(GaiaAuthFetcher::kClientLoginToOAuth2CookiePartCodePrefix
) - 1;
176 GaiaAuthFetcher::GaiaAuthFetcher(GaiaAuthConsumer
* consumer
,
177 const std::string
& source
,
178 net::URLRequestContextGetter
* getter
)
179 : consumer_(consumer
),
182 client_login_gurl_(GaiaUrls::GetInstance()->client_login_url()),
183 issue_auth_token_gurl_(GaiaUrls::GetInstance()->issue_auth_token_url()),
184 oauth2_token_gurl_(GaiaUrls::GetInstance()->oauth2_token_url()),
185 oauth2_revoke_gurl_(GaiaUrls::GetInstance()->oauth2_revoke_url()),
186 get_user_info_gurl_(GaiaUrls::GetInstance()->get_user_info_url()),
187 merge_session_gurl_(GaiaUrls::GetInstance()->merge_session_url()),
188 uberauth_token_gurl_(GaiaUrls::GetInstance()->oauth1_login_url().Resolve(
189 base::StringPrintf(kUberAuthTokenURLFormat
, source
.c_str()))),
190 oauth_login_gurl_(GaiaUrls::GetInstance()->oauth1_login_url()),
192 GaiaUrls::GetInstance()->ListAccountsURLWithSource(source
)),
193 get_check_connection_info_url_(
194 GaiaUrls::GetInstance()->GetCheckConnectionInfoURLWithSource(source
)),
195 client_login_to_oauth2_gurl_(
196 GaiaUrls::GetInstance()->client_login_to_oauth2_url()),
197 fetch_pending_(false) {}
199 GaiaAuthFetcher::~GaiaAuthFetcher() {}
201 bool GaiaAuthFetcher::HasPendingFetch() {
202 return fetch_pending_
;
205 void GaiaAuthFetcher::CancelRequest() {
207 fetch_pending_
= false;
211 net::URLFetcher
* GaiaAuthFetcher::CreateGaiaFetcher(
212 net::URLRequestContextGetter
* getter
,
213 const std::string
& body
,
214 const std::string
& headers
,
215 const GURL
& gaia_gurl
,
217 net::URLFetcherDelegate
* delegate
) {
218 net::URLFetcher
* to_return
= net::URLFetcher::Create(
220 body
.empty() ? net::URLFetcher::GET
: net::URLFetcher::POST
,
222 to_return
->SetRequestContext(getter
);
223 to_return
->SetUploadData("application/x-www-form-urlencoded", body
);
225 DVLOG(2) << "Gaia fetcher URL: " << gaia_gurl
.spec();
226 DVLOG(2) << "Gaia fetcher headers: " << headers
;
227 DVLOG(2) << "Gaia fetcher body: " << body
;
229 // The Gaia token exchange requests do not require any cookie-based
230 // identification as part of requests. We suppress sending any cookies to
231 // maintain a separation between the user's browsing and Chrome's internal
232 // services. Where such mixing is desired (MergeSession or OAuthLogin), it
233 // will be done explicitly.
234 to_return
->SetLoadFlags(load_flags
);
236 // Fetchers are sometimes cancelled because a network change was detected,
237 // especially at startup and after sign-in on ChromeOS. Retrying once should
238 // be enough in those cases; let the fetcher retry up to 3 times just in case.
239 // http://crbug.com/163710
240 to_return
->SetAutomaticallyRetryOnNetworkChanges(3);
242 if (!headers
.empty())
243 to_return
->SetExtraRequestHeaders(headers
);
249 std::string
GaiaAuthFetcher::MakeClientLoginBody(
250 const std::string
& username
,
251 const std::string
& password
,
252 const std::string
& source
,
254 const std::string
& login_token
,
255 const std::string
& login_captcha
,
256 HostedAccountsSetting allow_hosted_accounts
) {
257 std::string encoded_username
= net::EscapeUrlEncodedData(username
, true);
258 std::string encoded_password
= net::EscapeUrlEncodedData(password
, true);
259 std::string encoded_login_token
= net::EscapeUrlEncodedData(login_token
,
261 std::string encoded_login_captcha
= net::EscapeUrlEncodedData(login_captcha
,
264 const char* account_type
= allow_hosted_accounts
== HostedAccountsAllowed
?
265 kAccountTypeHostedOrGoogle
:
268 if (login_token
.empty() || login_captcha
.empty()) {
269 return base::StringPrintf(kClientLoginFormat
,
270 encoded_username
.c_str(),
271 encoded_password
.c_str(),
278 return base::StringPrintf(kClientLoginCaptchaFormat
,
279 encoded_username
.c_str(),
280 encoded_password
.c_str(),
285 encoded_login_token
.c_str(),
286 encoded_login_captcha
.c_str());
290 std::string
GaiaAuthFetcher::MakeIssueAuthTokenBody(
291 const std::string
& sid
,
292 const std::string
& lsid
,
293 const char* const service
) {
294 std::string encoded_sid
= net::EscapeUrlEncodedData(sid
, true);
295 std::string encoded_lsid
= net::EscapeUrlEncodedData(lsid
, true);
297 // All tokens should be session tokens except the gaia auth token.
299 if (!strcmp(service
, GaiaConstants::kGaiaService
))
302 return base::StringPrintf(kIssueAuthTokenFormat
,
304 encoded_lsid
.c_str(),
306 session
? "true" : "false");
310 std::string
GaiaAuthFetcher::MakeGetAuthCodeBody(bool include_device_type
) {
311 std::string encoded_scope
= net::EscapeUrlEncodedData(
312 GaiaConstants::kOAuth1LoginScope
, true);
313 std::string encoded_client_id
= net::EscapeUrlEncodedData(
314 GaiaUrls::GetInstance()->oauth2_chrome_client_id(), true);
315 if (include_device_type
) {
316 return base::StringPrintf(kClientLoginToOAuth2WithDeviceTypeBodyFormat
,
317 encoded_scope
.c_str(),
318 encoded_client_id
.c_str());
320 return base::StringPrintf(kClientLoginToOAuth2BodyFormat
,
321 encoded_scope
.c_str(),
322 encoded_client_id
.c_str());
327 std::string
GaiaAuthFetcher::MakeGetTokenPairBody(
328 const std::string
& auth_code
) {
329 std::string encoded_scope
= net::EscapeUrlEncodedData(
330 GaiaConstants::kOAuth1LoginScope
, true);
331 std::string encoded_client_id
= net::EscapeUrlEncodedData(
332 GaiaUrls::GetInstance()->oauth2_chrome_client_id(), true);
333 std::string encoded_client_secret
= net::EscapeUrlEncodedData(
334 GaiaUrls::GetInstance()->oauth2_chrome_client_secret(), true);
335 std::string encoded_auth_code
= net::EscapeUrlEncodedData(auth_code
, true);
336 return base::StringPrintf(kOAuth2CodeToTokenPairBodyFormat
,
337 encoded_scope
.c_str(),
338 encoded_client_id
.c_str(),
339 encoded_client_secret
.c_str(),
340 encoded_auth_code
.c_str());
344 std::string
GaiaAuthFetcher::MakeRevokeTokenBody(
345 const std::string
& auth_token
) {
346 return base::StringPrintf(kOAuth2RevokeTokenBodyFormat
, auth_token
.c_str());
350 std::string
GaiaAuthFetcher::MakeGetUserInfoBody(const std::string
& lsid
) {
351 std::string encoded_lsid
= net::EscapeUrlEncodedData(lsid
, true);
352 return base::StringPrintf(kGetUserInfoFormat
, encoded_lsid
.c_str());
356 std::string
GaiaAuthFetcher::MakeMergeSessionBody(
357 const std::string
& auth_token
,
358 const std::string
& external_cc_result
,
359 const std::string
& continue_url
,
360 const std::string
& source
) {
361 std::string encoded_auth_token
= net::EscapeUrlEncodedData(auth_token
, true);
362 std::string encoded_continue_url
= net::EscapeUrlEncodedData(continue_url
,
364 std::string encoded_source
= net::EscapeUrlEncodedData(source
, true);
365 std::string result
= base::StringPrintf(kMergeSessionFormat
,
366 encoded_auth_token
.c_str(),
367 encoded_continue_url
.c_str(),
368 encoded_source
.c_str());
369 if (!external_cc_result
.empty()) {
370 base::StringAppendF(&result
, "&externalCcResult=%s",
371 net::EscapeUrlEncodedData(
372 external_cc_result
, true).c_str());
379 std::string
GaiaAuthFetcher::MakeGetAuthCodeHeader(
380 const std::string
& auth_token
) {
381 return base::StringPrintf(kAuthHeaderFormat
, auth_token
.c_str());
384 // Helper method that extracts tokens from a successful reply.
386 void GaiaAuthFetcher::ParseClientLoginResponse(const std::string
& data
,
389 std::string
* token
) {
396 vector
<pair
<string
, string
> > tokens
;
397 base::SplitStringIntoKeyValuePairs(data
, '=', '\n', &tokens
);
398 for (vector
<pair
<string
, string
> >::iterator i
= tokens
.begin();
399 i
!= tokens
.end(); ++i
) {
400 if (i
->first
== "SID") {
401 sid
->assign(i
->second
);
402 } else if (i
->first
== "LSID") {
403 lsid
->assign(i
->second
);
404 } else if (i
->first
== "Auth") {
405 token
->assign(i
->second
);
408 // If this was a request for uberauth token, then that's all we've got in
410 if (sid
->empty() && lsid
->empty() && token
->empty())
415 std::string
GaiaAuthFetcher::MakeOAuthLoginBody(const std::string
& service
,
416 const std::string
& source
) {
417 std::string encoded_service
= net::EscapeUrlEncodedData(service
, true);
418 std::string encoded_source
= net::EscapeUrlEncodedData(source
, true);
419 return base::StringPrintf(kOAuthLoginFormat
,
420 encoded_service
.c_str(),
421 encoded_source
.c_str());
425 void GaiaAuthFetcher::ParseClientLoginFailure(const std::string
& data
,
427 std::string
* error_url
,
428 std::string
* captcha_url
,
429 std::string
* captcha_token
) {
434 vector
<pair
<string
, string
> > tokens
;
435 base::SplitStringIntoKeyValuePairs(data
, '=', '\n', &tokens
);
436 for (vector
<pair
<string
, string
> >::iterator i
= tokens
.begin();
437 i
!= tokens
.end(); ++i
) {
438 if (i
->first
== kErrorParam
) {
439 error
->assign(i
->second
);
440 } else if (i
->first
== kErrorUrlParam
) {
441 error_url
->assign(i
->second
);
442 } else if (i
->first
== kCaptchaUrlParam
) {
443 captcha_url
->assign(i
->second
);
444 } else if (i
->first
== kCaptchaTokenParam
) {
445 captcha_token
->assign(i
->second
);
451 bool GaiaAuthFetcher::ParseClientLoginToOAuth2Response(
452 const net::ResponseCookies
& cookies
,
453 std::string
* auth_code
) {
455 net::ResponseCookies::const_iterator iter
;
456 for (iter
= cookies
.begin(); iter
!= cookies
.end(); ++iter
) {
457 if (ParseClientLoginToOAuth2Cookie(*iter
, auth_code
))
464 bool GaiaAuthFetcher::ParseClientLoginToOAuth2Cookie(const std::string
& cookie
,
465 std::string
* auth_code
) {
466 std::vector
<std::string
> parts
;
467 base::SplitString(cookie
, ';', &parts
);
468 // Per documentation, the cookie should have Secure and HttpOnly.
469 if (!CookiePartsContains(parts
, kClientLoginToOAuth2CookiePartSecure
) ||
470 !CookiePartsContains(parts
, kClientLoginToOAuth2CookiePartHttpOnly
)) {
474 std::vector
<std::string
>::const_iterator iter
;
475 for (iter
= parts
.begin(); iter
!= parts
.end(); ++iter
) {
476 const std::string
& part
= *iter
;
478 part
, kClientLoginToOAuth2CookiePartCodePrefix
, false)) {
479 auth_code
->assign(part
.substr(
480 kClientLoginToOAuth2CookiePartCodePrefixLength
));
487 void GaiaAuthFetcher::StartClientLogin(
488 const std::string
& username
,
489 const std::string
& password
,
490 const char* const service
,
491 const std::string
& login_token
,
492 const std::string
& login_captcha
,
493 HostedAccountsSetting allow_hosted_accounts
) {
495 DCHECK(!fetch_pending_
) << "Tried to fetch two things at once!";
497 // This class is thread agnostic, so be sure to call this only on the
498 // same thread each time.
499 DVLOG(1) << "Starting new ClientLogin fetch for:" << username
;
501 // Must outlive fetcher_.
502 request_body_
= MakeClientLoginBody(username
,
508 allow_hosted_accounts
);
509 fetcher_
.reset(CreateGaiaFetcher(getter_
,
513 kLoadFlagsIgnoreCookies
,
515 fetch_pending_
= true;
519 void GaiaAuthFetcher::StartIssueAuthToken(const std::string
& sid
,
520 const std::string
& lsid
,
521 const char* const service
) {
522 DCHECK(!fetch_pending_
) << "Tried to fetch two things at once!";
524 DVLOG(1) << "Starting IssueAuthToken for: " << service
;
525 requested_service_
= service
;
526 request_body_
= MakeIssueAuthTokenBody(sid
, lsid
, service
);
527 fetcher_
.reset(CreateGaiaFetcher(getter_
,
530 issue_auth_token_gurl_
,
531 kLoadFlagsIgnoreCookies
,
533 fetch_pending_
= true;
537 void GaiaAuthFetcher::StartLsoForOAuthLoginTokenExchange(
538 const std::string
& auth_token
) {
539 DCHECK(!fetch_pending_
) << "Tried to fetch two things at once!";
541 DVLOG(1) << "Starting OAuth login token exchange with auth_token";
542 request_body_
= MakeGetAuthCodeBody(false);
543 client_login_to_oauth2_gurl_
=
544 GaiaUrls::GetInstance()->client_login_to_oauth2_url();
546 fetcher_
.reset(CreateGaiaFetcher(getter_
,
548 MakeGetAuthCodeHeader(auth_token
),
549 client_login_to_oauth2_gurl_
,
550 kLoadFlagsIgnoreCookies
,
552 fetch_pending_
= true;
556 void GaiaAuthFetcher::StartRevokeOAuth2Token(const std::string
& auth_token
) {
557 DCHECK(!fetch_pending_
) << "Tried to fetch two things at once!";
559 DVLOG(1) << "Starting OAuth2 token revocation";
560 request_body_
= MakeRevokeTokenBody(auth_token
);
561 fetcher_
.reset(CreateGaiaFetcher(getter_
,
565 kLoadFlagsIgnoreCookies
,
567 fetch_pending_
= true;
571 void GaiaAuthFetcher::StartCookieForOAuthLoginTokenExchange(
572 const std::string
& session_index
) {
573 StartCookieForOAuthLoginTokenExchangeWithDeviceId(session_index
,
577 void GaiaAuthFetcher::StartCookieForOAuthLoginTokenExchangeWithDeviceId(
578 const std::string
& session_index
,
579 const std::string
& device_id
) {
580 DCHECK(!fetch_pending_
) << "Tried to fetch two things at once!";
582 DVLOG(1) << "Starting OAuth login token fetch with cookie jar";
583 request_body_
= MakeGetAuthCodeBody(!device_id
.empty());
585 client_login_to_oauth2_gurl_
=
586 GaiaUrls::GetInstance()->client_login_to_oauth2_url();
587 if (!session_index
.empty()) {
588 client_login_to_oauth2_gurl_
=
589 client_login_to_oauth2_gurl_
.Resolve("?authuser=" + session_index
);
592 std::string device_id_header
;
593 if (!device_id
.empty()) {
595 base::StringPrintf(kDeviceIdHeaderFormat
, device_id
.c_str());
598 fetcher_
.reset(CreateGaiaFetcher(getter_
,
601 client_login_to_oauth2_gurl_
,
604 fetch_pending_
= true;
608 void GaiaAuthFetcher::StartAuthCodeForOAuth2TokenExchange(
609 const std::string
& auth_code
) {
610 DCHECK(!fetch_pending_
) << "Tried to fetch two things at once!";
612 DVLOG(1) << "Starting OAuth token pair fetch";
613 request_body_
= MakeGetTokenPairBody(auth_code
);
614 fetcher_
.reset(CreateGaiaFetcher(getter_
,
618 kLoadFlagsIgnoreCookies
,
620 fetch_pending_
= true;
624 void GaiaAuthFetcher::StartGetUserInfo(const std::string
& lsid
) {
625 DCHECK(!fetch_pending_
) << "Tried to fetch two things at once!";
627 DVLOG(1) << "Starting GetUserInfo for lsid=" << lsid
;
628 request_body_
= MakeGetUserInfoBody(lsid
);
629 fetcher_
.reset(CreateGaiaFetcher(getter_
,
633 kLoadFlagsIgnoreCookies
,
635 fetch_pending_
= true;
639 void GaiaAuthFetcher::StartMergeSession(const std::string
& uber_token
,
640 const std::string
& external_cc_result
) {
641 DCHECK(!fetch_pending_
) << "Tried to fetch two things at once!";
643 DVLOG(1) << "Starting MergeSession with uber_token=" << uber_token
;
645 // The continue URL is a required parameter of the MergeSession API, but in
646 // this case we don't actually need or want to navigate to it. Setting it to
647 // an arbitrary Google URL.
649 // In order for the new session to be merged correctly, the server needs to
650 // know what sessions already exist in the browser. The fetcher needs to be
651 // created such that it sends the cookies with the request, which is
652 // different from all other requests the fetcher can make.
653 std::string
continue_url("http://www.google.com");
654 request_body_
= MakeMergeSessionBody(uber_token
, external_cc_result
,
655 continue_url
, source_
);
656 fetcher_
.reset(CreateGaiaFetcher(getter_
,
662 fetch_pending_
= true;
666 void GaiaAuthFetcher::StartTokenFetchForUberAuthExchange(
667 const std::string
& access_token
) {
668 DCHECK(!fetch_pending_
) << "Tried to fetch two things at once!";
670 DVLOG(1) << "Starting StartTokenFetchForUberAuthExchange with access_token="
672 std::string authentication_header
=
673 base::StringPrintf(kOAuthHeaderFormat
, access_token
.c_str());
674 fetcher_
.reset(CreateGaiaFetcher(getter_
,
676 authentication_header
,
677 uberauth_token_gurl_
,
680 fetch_pending_
= true;
684 void GaiaAuthFetcher::StartOAuthLogin(const std::string
& access_token
,
685 const std::string
& service
) {
686 DCHECK(!fetch_pending_
) << "Tried to fetch two things at once!";
688 request_body_
= MakeOAuthLoginBody(service
, source_
);
689 std::string authentication_header
=
690 base::StringPrintf(kOAuth2BearerHeaderFormat
, access_token
.c_str());
691 fetcher_
.reset(CreateGaiaFetcher(getter_
,
693 authentication_header
,
697 fetch_pending_
= true;
701 void GaiaAuthFetcher::StartListAccounts() {
702 DCHECK(!fetch_pending_
) << "Tried to fetch two things at once!";
704 fetcher_
.reset(CreateGaiaFetcher(getter_
,
705 " ", // To force an HTTP POST.
706 "Origin: https://www.google.com",
710 fetch_pending_
= true;
714 void GaiaAuthFetcher::StartGetCheckConnectionInfo() {
715 DCHECK(!fetch_pending_
) << "Tried to fetch two things at once!";
717 fetcher_
.reset(CreateGaiaFetcher(getter_
,
720 get_check_connection_info_url_
,
721 kLoadFlagsIgnoreCookies
,
723 fetch_pending_
= true;
728 GoogleServiceAuthError
GaiaAuthFetcher::GenerateAuthError(
729 const std::string
& data
,
730 const net::URLRequestStatus
& status
) {
731 if (!status
.is_success()) {
732 if (status
.status() == net::URLRequestStatus::CANCELED
) {
733 return GoogleServiceAuthError(GoogleServiceAuthError::REQUEST_CANCELED
);
735 DLOG(WARNING
) << "Could not reach Google Accounts servers: errno "
737 return GoogleServiceAuthError::FromConnectionError(status
.error());
740 if (IsSecondFactorSuccess(data
))
741 return GoogleServiceAuthError(GoogleServiceAuthError::TWO_FACTOR
);
743 if (IsWebLoginRequiredSuccess(data
))
744 return GoogleServiceAuthError(GoogleServiceAuthError::WEB_LOGIN_REQUIRED
);
748 std::string captcha_url
;
749 std::string captcha_token
;
750 ParseClientLoginFailure(data
, &error
, &url
, &captcha_url
, &captcha_token
);
751 DLOG(WARNING
) << "ClientLogin failed with " << error
;
753 if (error
== kCaptchaError
) {
754 return GoogleServiceAuthError::FromClientLoginCaptchaChallenge(
756 GURL(GaiaUrls::GetInstance()->captcha_base_url().Resolve(captcha_url
)),
759 if (error
== kAccountDeletedError
)
760 return GoogleServiceAuthError(GoogleServiceAuthError::ACCOUNT_DELETED
);
761 if (error
== kAccountDisabledError
)
762 return GoogleServiceAuthError(GoogleServiceAuthError::ACCOUNT_DISABLED
);
763 if (error
== kBadAuthenticationError
) {
764 return GoogleServiceAuthError(
765 GoogleServiceAuthError::INVALID_GAIA_CREDENTIALS
);
767 if (error
== kServiceUnavailableError
) {
768 return GoogleServiceAuthError(
769 GoogleServiceAuthError::SERVICE_UNAVAILABLE
);
772 DLOG(WARNING
) << "Incomprehensible response from Google Accounts servers.";
773 return GoogleServiceAuthError(GoogleServiceAuthError::SERVICE_UNAVAILABLE
);
776 void GaiaAuthFetcher::OnClientLoginFetched(const std::string
& data
,
777 const net::URLRequestStatus
& status
,
779 if (status
.is_success() && response_code
== net::HTTP_OK
) {
780 DVLOG(1) << "ClientLogin successful!";
784 ParseClientLoginResponse(data
, &sid
, &lsid
, &token
);
785 consumer_
->OnClientLoginSuccess(
786 GaiaAuthConsumer::ClientLoginResult(sid
, lsid
, token
, data
));
788 consumer_
->OnClientLoginFailure(GenerateAuthError(data
, status
));
792 void GaiaAuthFetcher::OnIssueAuthTokenFetched(
793 const std::string
& data
,
794 const net::URLRequestStatus
& status
,
796 if (status
.is_success() && response_code
== net::HTTP_OK
) {
797 // Only the bare token is returned in the body of this Gaia call
798 // without any padding.
799 consumer_
->OnIssueAuthTokenSuccess(requested_service_
, data
);
801 consumer_
->OnIssueAuthTokenFailure(requested_service_
,
802 GenerateAuthError(data
, status
));
806 void GaiaAuthFetcher::OnClientLoginToOAuth2Fetched(
807 const std::string
& data
,
808 const net::ResponseCookies
& cookies
,
809 const net::URLRequestStatus
& status
,
811 if (status
.is_success() && response_code
== net::HTTP_OK
) {
812 std::string auth_code
;
813 if (ParseClientLoginToOAuth2Response(cookies
, &auth_code
)) {
814 StartAuthCodeForOAuth2TokenExchange(auth_code
);
816 GoogleServiceAuthError
auth_error(
817 GoogleServiceAuthError::FromUnexpectedServiceResponse(
818 "ClientLogin response cookies didn't contain an auth code"));
819 consumer_
->OnClientOAuthFailure(auth_error
);
822 GoogleServiceAuthError
auth_error(GenerateAuthError(data
, status
));
823 consumer_
->OnClientOAuthFailure(auth_error
);
827 void GaiaAuthFetcher::OnOAuth2TokenPairFetched(
828 const std::string
& data
,
829 const net::URLRequestStatus
& status
,
831 std::string refresh_token
;
832 std::string access_token
;
833 int expires_in_secs
= 0;
835 bool success
= false;
836 if (status
.is_success() && response_code
== net::HTTP_OK
) {
837 scoped_ptr
<base::Value
> value(base::JSONReader::Read(data
));
838 if (value
.get() && value
->GetType() == base::Value::TYPE_DICTIONARY
) {
839 base::DictionaryValue
* dict
=
840 static_cast<base::DictionaryValue
*>(value
.get());
841 success
= ExtractOAuth2TokenPairResponse(dict
, &refresh_token
,
842 &access_token
, &expires_in_secs
);
847 consumer_
->OnClientOAuthSuccess(
848 GaiaAuthConsumer::ClientOAuthResult(refresh_token
, access_token
,
851 consumer_
->OnClientOAuthFailure(GenerateAuthError(data
, status
));
855 void GaiaAuthFetcher::OnOAuth2RevokeTokenFetched(
856 const std::string
& data
,
857 const net::URLRequestStatus
& status
,
859 consumer_
->OnOAuth2RevokeTokenCompleted();
862 void GaiaAuthFetcher::OnListAccountsFetched(const std::string
& data
,
863 const net::URLRequestStatus
& status
,
865 if (status
.is_success() && response_code
== net::HTTP_OK
) {
866 consumer_
->OnListAccountsSuccess(data
);
868 consumer_
->OnListAccountsFailure(GenerateAuthError(data
, status
));
872 void GaiaAuthFetcher::OnGetUserInfoFetched(
873 const std::string
& data
,
874 const net::URLRequestStatus
& status
,
876 if (status
.is_success() && response_code
== net::HTTP_OK
) {
877 base::StringPairs tokens
;
879 base::SplitStringIntoKeyValuePairs(data
, '=', '\n', &tokens
);
880 base::StringPairs::iterator i
;
881 for (i
= tokens
.begin(); i
!= tokens
.end(); ++i
) {
882 matches
[i
->first
] = i
->second
;
884 consumer_
->OnGetUserInfoSuccess(matches
);
886 consumer_
->OnGetUserInfoFailure(GenerateAuthError(data
, status
));
890 void GaiaAuthFetcher::OnMergeSessionFetched(const std::string
& data
,
891 const net::URLRequestStatus
& status
,
893 if (status
.is_success() && response_code
== net::HTTP_OK
) {
894 consumer_
->OnMergeSessionSuccess(data
);
896 consumer_
->OnMergeSessionFailure(GenerateAuthError(data
, status
));
900 void GaiaAuthFetcher::OnUberAuthTokenFetch(const std::string
& data
,
901 const net::URLRequestStatus
& status
,
903 if (status
.is_success() && response_code
== net::HTTP_OK
) {
904 consumer_
->OnUberAuthTokenSuccess(data
);
906 consumer_
->OnUberAuthTokenFailure(GenerateAuthError(data
, status
));
910 void GaiaAuthFetcher::OnOAuthLoginFetched(const std::string
& data
,
911 const net::URLRequestStatus
& status
,
913 if (status
.is_success() && response_code
== net::HTTP_OK
) {
914 DVLOG(1) << "ClientLogin successful!";
918 ParseClientLoginResponse(data
, &sid
, &lsid
, &token
);
919 consumer_
->OnClientLoginSuccess(
920 GaiaAuthConsumer::ClientLoginResult(sid
, lsid
, token
, data
));
922 consumer_
->OnClientLoginFailure(GenerateAuthError(data
, status
));
926 void GaiaAuthFetcher::OnGetCheckConnectionInfoFetched(
927 const std::string
& data
,
928 const net::URLRequestStatus
& status
,
930 if (status
.is_success() && response_code
== net::HTTP_OK
) {
931 consumer_
->OnGetCheckConnectionInfoSuccess(data
);
933 consumer_
->OnGetCheckConnectionInfoError(GenerateAuthError(data
, status
));
937 void GaiaAuthFetcher::OnURLFetchComplete(const net::URLFetcher
* source
) {
938 fetch_pending_
= false;
939 // Some of the GAIA requests perform redirects, which results in the final
940 // URL of the fetcher not being the original URL requested. Therefore use
941 // the original URL when determining which OnXXX function to call.
942 const GURL
& url
= source
->GetOriginalURL();
943 const net::URLRequestStatus
& status
= source
->GetStatus();
944 int response_code
= source
->GetResponseCode();
946 source
->GetResponseAsString(&data
);
949 if (source
->GetResponseHeaders())
950 source
->GetResponseHeaders()->GetNormalizedHeaders(&headers
);
951 DVLOG(2) << "Response " << url
.spec() << ", code = " << response_code
<< "\n"
953 DVLOG(2) << "data: " << data
<< "\n";
955 // Retrieve the response headers from the request. Must only be called after
956 // the OnURLFetchComplete callback has run.
957 if (url
== client_login_gurl_
) {
958 OnClientLoginFetched(data
, status
, response_code
);
959 } else if (url
== issue_auth_token_gurl_
) {
960 OnIssueAuthTokenFetched(data
, status
, response_code
);
961 } else if (url
== client_login_to_oauth2_gurl_
) {
962 OnClientLoginToOAuth2Fetched(
963 data
, source
->GetCookies(), status
, response_code
);
964 } else if (url
== oauth2_token_gurl_
) {
965 OnOAuth2TokenPairFetched(data
, status
, response_code
);
966 } else if (url
== get_user_info_gurl_
) {
967 OnGetUserInfoFetched(data
, status
, response_code
);
968 } else if (url
== merge_session_gurl_
) {
969 OnMergeSessionFetched(data
, status
, response_code
);
970 } else if (url
== uberauth_token_gurl_
) {
971 OnUberAuthTokenFetch(data
, status
, response_code
);
972 } else if (url
== oauth_login_gurl_
) {
973 OnOAuthLoginFetched(data
, status
, response_code
);
974 } else if (url
== oauth2_revoke_gurl_
) {
975 OnOAuth2RevokeTokenFetched(data
, status
, response_code
);
976 } else if (url
== list_accounts_gurl_
) {
977 OnListAccountsFetched(data
, status
, response_code
);
978 } else if (url
== get_check_connection_info_url_
) {
979 OnGetCheckConnectionInfoFetched(data
, status
, response_code
);
986 bool GaiaAuthFetcher::IsSecondFactorSuccess(
987 const std::string
& alleged_error
) {
988 return alleged_error
.find(kSecondFactor
) !=
993 bool GaiaAuthFetcher::IsWebLoginRequiredSuccess(
994 const std::string
& alleged_error
) {
995 return alleged_error
.find(kWebLoginRequired
) !=