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 // From the JSON string |data|, extract the |access_token| and |expires_in_secs|
45 // both of which must exist. If the |refresh_token| is non-NULL, then it also
46 // must exist and is extraced; if it's NULL, then no extraction is attempted.
47 bool ExtractOAuth2TokenPairResponse(const std::string
& data
,
48 std::string
* refresh_token
,
49 std::string
* access_token
,
50 int* expires_in_secs
) {
52 DCHECK(expires_in_secs
);
54 scoped_ptr
<base::Value
> value(base::JSONReader::Read(data
));
55 if (!value
.get() || value
->GetType() != base::Value::TYPE_DICTIONARY
)
58 base::DictionaryValue
* dict
=
59 static_cast<base::DictionaryValue
*>(value
.get());
61 if (!dict
->GetStringWithoutPathExpansion("access_token", access_token
) ||
62 !dict
->GetIntegerWithoutPathExpansion("expires_in", expires_in_secs
)) {
66 // Refresh token may not be required.
68 if (!dict
->GetStringWithoutPathExpansion("refresh_token", refresh_token
))
74 const char kListIdpServiceRequested
[] = "list_idp";
75 const char kGetTokenResponseRequested
[] = "get_token";
79 // TODO(chron): Add sourceless version of this formatter.
81 const char GaiaAuthFetcher::kClientLoginFormat
[] =
84 "PersistentCookie=%s&"
89 const char GaiaAuthFetcher::kClientLoginCaptchaFormat
[] =
92 "PersistentCookie=%s&"
99 const char GaiaAuthFetcher::kIssueAuthTokenFormat
[] =
105 const char GaiaAuthFetcher::kClientLoginToOAuth2BodyFormat
[] =
106 "scope=%s&client_id=%s";
108 const char GaiaAuthFetcher::kClientLoginToOAuth2WithDeviceTypeBodyFormat
[] =
109 "scope=%s&client_id=%s&device_type=chrome";
111 const char GaiaAuthFetcher::kOAuth2CodeToTokenPairBodyFormat
[] =
113 "grant_type=authorization_code&"
118 const char GaiaAuthFetcher::kOAuth2CodeToTokenPairDeviceIdParam
[] =
119 "device_id=%s&device_type=chrome";
121 const char GaiaAuthFetcher::kOAuth2RevokeTokenBodyFormat
[] =
124 const char GaiaAuthFetcher::kGetUserInfoFormat
[] =
127 const char GaiaAuthFetcher::kMergeSessionFormat
[] =
132 const char GaiaAuthFetcher::kUberAuthTokenURLFormat
[] =
136 const char GaiaAuthFetcher::kOAuthLoginFormat
[] = "service=%s&source=%s";
139 const char GaiaAuthFetcher::kAccountDeletedError
[] = "AccountDeleted";
141 const char GaiaAuthFetcher::kAccountDisabledError
[] = "AccountDisabled";
143 const char GaiaAuthFetcher::kBadAuthenticationError
[] = "BadAuthentication";
145 const char GaiaAuthFetcher::kCaptchaError
[] = "CaptchaRequired";
147 const char GaiaAuthFetcher::kServiceUnavailableError
[] =
148 "ServiceUnavailable";
150 const char GaiaAuthFetcher::kErrorParam
[] = "Error";
152 const char GaiaAuthFetcher::kErrorUrlParam
[] = "Url";
154 const char GaiaAuthFetcher::kCaptchaUrlParam
[] = "CaptchaUrl";
156 const char GaiaAuthFetcher::kCaptchaTokenParam
[] = "CaptchaToken";
159 const char GaiaAuthFetcher::kCookiePersistence
[] = "true";
161 // TODO(johnnyg): When hosted accounts are supported by sync,
162 // we can always use "HOSTED_OR_GOOGLE"
163 const char GaiaAuthFetcher::kAccountTypeHostedOrGoogle
[] =
165 const char GaiaAuthFetcher::kAccountTypeGoogle
[] =
169 const char GaiaAuthFetcher::kSecondFactor
[] = "Info=InvalidSecondFactor";
171 const char GaiaAuthFetcher::kWebLoginRequired
[] = "Info=WebLoginRequired";
174 const char GaiaAuthFetcher::kAuthHeaderFormat
[] =
175 "Authorization: GoogleLogin auth=%s";
177 const char GaiaAuthFetcher::kOAuthHeaderFormat
[] = "Authorization: OAuth %s";
179 const char GaiaAuthFetcher::kOAuth2BearerHeaderFormat
[] =
180 "Authorization: Bearer %s";
182 const char GaiaAuthFetcher::kDeviceIdHeaderFormat
[] = "X-Device-ID: %s";
184 const char GaiaAuthFetcher::kClientLoginToOAuth2CookiePartSecure
[] = "secure";
186 const char GaiaAuthFetcher::kClientLoginToOAuth2CookiePartHttpOnly
[] =
189 const char GaiaAuthFetcher::kClientLoginToOAuth2CookiePartCodePrefix
[] =
192 const int GaiaAuthFetcher::kClientLoginToOAuth2CookiePartCodePrefixLength
=
193 arraysize(GaiaAuthFetcher::kClientLoginToOAuth2CookiePartCodePrefix
) - 1;
195 GaiaAuthFetcher::GaiaAuthFetcher(GaiaAuthConsumer
* consumer
,
196 const std::string
& source
,
197 net::URLRequestContextGetter
* getter
)
198 : consumer_(consumer
),
201 client_login_gurl_(GaiaUrls::GetInstance()->client_login_url()),
202 issue_auth_token_gurl_(GaiaUrls::GetInstance()->issue_auth_token_url()),
203 oauth2_token_gurl_(GaiaUrls::GetInstance()->oauth2_token_url()),
204 oauth2_revoke_gurl_(GaiaUrls::GetInstance()->oauth2_revoke_url()),
205 get_user_info_gurl_(GaiaUrls::GetInstance()->get_user_info_url()),
206 merge_session_gurl_(GaiaUrls::GetInstance()->merge_session_url()),
207 uberauth_token_gurl_(GaiaUrls::GetInstance()->oauth1_login_url().Resolve(
208 base::StringPrintf(kUberAuthTokenURLFormat
, source
.c_str()))),
209 oauth_login_gurl_(GaiaUrls::GetInstance()->oauth1_login_url()),
211 GaiaUrls::GetInstance()->ListAccountsURLWithSource(source
)),
212 get_check_connection_info_url_(
213 GaiaUrls::GetInstance()->GetCheckConnectionInfoURLWithSource(source
)),
214 oauth2_iframe_url_(GaiaUrls::GetInstance()->oauth2_iframe_url()),
215 client_login_to_oauth2_gurl_(
216 GaiaUrls::GetInstance()->client_login_to_oauth2_url()),
217 fetch_pending_(false) {}
219 GaiaAuthFetcher::~GaiaAuthFetcher() {}
221 bool GaiaAuthFetcher::HasPendingFetch() {
222 return fetch_pending_
;
225 void GaiaAuthFetcher::CancelRequest() {
227 fetch_pending_
= false;
231 scoped_ptr
<net::URLFetcher
> GaiaAuthFetcher::CreateGaiaFetcher(
232 net::URLRequestContextGetter
* getter
,
233 const std::string
& body
,
234 const std::string
& headers
,
235 const GURL
& gaia_gurl
,
237 net::URLFetcherDelegate
* delegate
) {
238 scoped_ptr
<net::URLFetcher
> to_return
= net::URLFetcher::Create(
239 0, gaia_gurl
, body
.empty() ? net::URLFetcher::GET
: net::URLFetcher::POST
,
241 to_return
->SetRequestContext(getter
);
242 to_return
->SetUploadData("application/x-www-form-urlencoded", body
);
244 DVLOG(2) << "Gaia fetcher URL: " << gaia_gurl
.spec();
245 DVLOG(2) << "Gaia fetcher headers: " << headers
;
246 DVLOG(2) << "Gaia fetcher body: " << body
;
248 // The Gaia token exchange requests do not require any cookie-based
249 // identification as part of requests. We suppress sending any cookies to
250 // maintain a separation between the user's browsing and Chrome's internal
251 // services. Where such mixing is desired (MergeSession or OAuthLogin), it
252 // will be done explicitly.
253 to_return
->SetLoadFlags(load_flags
);
255 // Fetchers are sometimes cancelled because a network change was detected,
256 // especially at startup and after sign-in on ChromeOS. Retrying once should
257 // be enough in those cases; let the fetcher retry up to 3 times just in case.
258 // http://crbug.com/163710
259 to_return
->SetAutomaticallyRetryOnNetworkChanges(3);
261 if (!headers
.empty())
262 to_return
->SetExtraRequestHeaders(headers
);
268 std::string
GaiaAuthFetcher::MakeClientLoginBody(
269 const std::string
& username
,
270 const std::string
& password
,
271 const std::string
& source
,
273 const std::string
& login_token
,
274 const std::string
& login_captcha
,
275 HostedAccountsSetting allow_hosted_accounts
) {
276 std::string encoded_username
= net::EscapeUrlEncodedData(username
, true);
277 std::string encoded_password
= net::EscapeUrlEncodedData(password
, true);
278 std::string encoded_login_token
= net::EscapeUrlEncodedData(login_token
,
280 std::string encoded_login_captcha
= net::EscapeUrlEncodedData(login_captcha
,
283 const char* account_type
= allow_hosted_accounts
== HostedAccountsAllowed
?
284 kAccountTypeHostedOrGoogle
:
287 if (login_token
.empty() || login_captcha
.empty()) {
288 return base::StringPrintf(kClientLoginFormat
,
289 encoded_username
.c_str(),
290 encoded_password
.c_str(),
297 return base::StringPrintf(kClientLoginCaptchaFormat
,
298 encoded_username
.c_str(),
299 encoded_password
.c_str(),
304 encoded_login_token
.c_str(),
305 encoded_login_captcha
.c_str());
309 std::string
GaiaAuthFetcher::MakeIssueAuthTokenBody(
310 const std::string
& sid
,
311 const std::string
& lsid
,
312 const char* const service
) {
313 std::string encoded_sid
= net::EscapeUrlEncodedData(sid
, true);
314 std::string encoded_lsid
= net::EscapeUrlEncodedData(lsid
, true);
316 // All tokens should be session tokens except the gaia auth token.
318 if (!strcmp(service
, GaiaConstants::kGaiaService
))
321 return base::StringPrintf(kIssueAuthTokenFormat
,
323 encoded_lsid
.c_str(),
325 session
? "true" : "false");
329 std::string
GaiaAuthFetcher::MakeGetAuthCodeBody(bool include_device_type
) {
330 std::string encoded_scope
= net::EscapeUrlEncodedData(
331 GaiaConstants::kOAuth1LoginScope
, true);
332 std::string encoded_client_id
= net::EscapeUrlEncodedData(
333 GaiaUrls::GetInstance()->oauth2_chrome_client_id(), true);
334 if (include_device_type
) {
335 return base::StringPrintf(kClientLoginToOAuth2WithDeviceTypeBodyFormat
,
336 encoded_scope
.c_str(),
337 encoded_client_id
.c_str());
339 return base::StringPrintf(kClientLoginToOAuth2BodyFormat
,
340 encoded_scope
.c_str(),
341 encoded_client_id
.c_str());
346 std::string
GaiaAuthFetcher::MakeGetTokenPairBody(
347 const std::string
& auth_code
,
348 const std::string
& device_id
) {
349 std::string encoded_scope
= net::EscapeUrlEncodedData(
350 GaiaConstants::kOAuth1LoginScope
, true);
351 std::string encoded_client_id
= net::EscapeUrlEncodedData(
352 GaiaUrls::GetInstance()->oauth2_chrome_client_id(), true);
353 std::string encoded_client_secret
= net::EscapeUrlEncodedData(
354 GaiaUrls::GetInstance()->oauth2_chrome_client_secret(), true);
355 std::string encoded_auth_code
= net::EscapeUrlEncodedData(auth_code
, true);
356 std::string body
= base::StringPrintf(
357 kOAuth2CodeToTokenPairBodyFormat
, encoded_scope
.c_str(),
358 encoded_client_id
.c_str(), encoded_client_secret
.c_str(),
359 encoded_auth_code
.c_str());
360 if (!device_id
.empty()) {
361 body
+= "&" + base::StringPrintf(kOAuth2CodeToTokenPairDeviceIdParam
,
368 std::string
GaiaAuthFetcher::MakeRevokeTokenBody(
369 const std::string
& auth_token
) {
370 return base::StringPrintf(kOAuth2RevokeTokenBodyFormat
, auth_token
.c_str());
374 std::string
GaiaAuthFetcher::MakeGetUserInfoBody(const std::string
& lsid
) {
375 std::string encoded_lsid
= net::EscapeUrlEncodedData(lsid
, true);
376 return base::StringPrintf(kGetUserInfoFormat
, encoded_lsid
.c_str());
380 std::string
GaiaAuthFetcher::MakeMergeSessionBody(
381 const std::string
& auth_token
,
382 const std::string
& external_cc_result
,
383 const std::string
& continue_url
,
384 const std::string
& source
) {
385 std::string encoded_auth_token
= net::EscapeUrlEncodedData(auth_token
, true);
386 std::string encoded_continue_url
= net::EscapeUrlEncodedData(continue_url
,
388 std::string encoded_source
= net::EscapeUrlEncodedData(source
, true);
389 std::string result
= base::StringPrintf(kMergeSessionFormat
,
390 encoded_auth_token
.c_str(),
391 encoded_continue_url
.c_str(),
392 encoded_source
.c_str());
393 if (!external_cc_result
.empty()) {
394 base::StringAppendF(&result
, "&externalCcResult=%s",
395 net::EscapeUrlEncodedData(
396 external_cc_result
, true).c_str());
403 std::string
GaiaAuthFetcher::MakeGetAuthCodeHeader(
404 const std::string
& auth_token
) {
405 return base::StringPrintf(kAuthHeaderFormat
, auth_token
.c_str());
408 // Helper method that extracts tokens from a successful reply.
410 void GaiaAuthFetcher::ParseClientLoginResponse(const std::string
& data
,
413 std::string
* token
) {
420 base::StringPairs tokens
;
421 base::SplitStringIntoKeyValuePairs(data
, '=', '\n', &tokens
);
422 for (base::StringPairs::iterator i
= tokens
.begin();
423 i
!= tokens
.end(); ++i
) {
424 if (i
->first
== "SID") {
425 sid
->assign(i
->second
);
426 } else if (i
->first
== "LSID") {
427 lsid
->assign(i
->second
);
428 } else if (i
->first
== "Auth") {
429 token
->assign(i
->second
);
432 // If this was a request for uberauth token, then that's all we've got in
434 if (sid
->empty() && lsid
->empty() && token
->empty())
439 std::string
GaiaAuthFetcher::MakeOAuthLoginBody(const std::string
& service
,
440 const std::string
& source
) {
441 std::string encoded_service
= net::EscapeUrlEncodedData(service
, true);
442 std::string encoded_source
= net::EscapeUrlEncodedData(source
, true);
443 return base::StringPrintf(kOAuthLoginFormat
,
444 encoded_service
.c_str(),
445 encoded_source
.c_str());
449 std::string
GaiaAuthFetcher::MakeListIDPSessionsBody(
450 const std::string
& scopes
,
451 const std::string
& domain
) {
452 static const char getTokenResponseBodyFormat
[] =
453 "action=listSessions&"
457 std::string encoded_client_id
= net::EscapeUrlEncodedData(
458 GaiaUrls::GetInstance()->oauth2_chrome_client_id(), true);
459 return base::StringPrintf(getTokenResponseBodyFormat
,
460 encoded_client_id
.c_str(),
465 std::string
GaiaAuthFetcher::MakeGetTokenResponseBody(
466 const std::string
& scopes
,
467 const std::string
& domain
,
468 const std::string
& login_hint
) {
469 static const char getTokenResponseBodyFormat
[] =
474 "response_type=token&"
476 std::string encoded_client_id
= net::EscapeUrlEncodedData(
477 GaiaUrls::GetInstance()->oauth2_chrome_client_id(), true);
478 return base::StringPrintf(getTokenResponseBodyFormat
,
479 encoded_client_id
.c_str(),
486 void GaiaAuthFetcher::ParseClientLoginFailure(const std::string
& data
,
488 std::string
* error_url
,
489 std::string
* captcha_url
,
490 std::string
* captcha_token
) {
495 base::StringPairs tokens
;
496 base::SplitStringIntoKeyValuePairs(data
, '=', '\n', &tokens
);
497 for (base::StringPairs::iterator i
= tokens
.begin();
498 i
!= tokens
.end(); ++i
) {
499 if (i
->first
== kErrorParam
) {
500 error
->assign(i
->second
);
501 } else if (i
->first
== kErrorUrlParam
) {
502 error_url
->assign(i
->second
);
503 } else if (i
->first
== kCaptchaUrlParam
) {
504 captcha_url
->assign(i
->second
);
505 } else if (i
->first
== kCaptchaTokenParam
) {
506 captcha_token
->assign(i
->second
);
512 bool GaiaAuthFetcher::ParseClientLoginToOAuth2Response(
513 const net::ResponseCookies
& cookies
,
514 std::string
* auth_code
) {
516 net::ResponseCookies::const_iterator iter
;
517 for (iter
= cookies
.begin(); iter
!= cookies
.end(); ++iter
) {
518 if (ParseClientLoginToOAuth2Cookie(*iter
, auth_code
))
525 bool GaiaAuthFetcher::ParseClientLoginToOAuth2Cookie(const std::string
& cookie
,
526 std::string
* auth_code
) {
527 std::vector
<std::string
> parts
;
528 base::SplitString(cookie
, ';', &parts
);
529 // Per documentation, the cookie should have Secure and HttpOnly.
530 if (!CookiePartsContains(parts
, kClientLoginToOAuth2CookiePartSecure
) ||
531 !CookiePartsContains(parts
, kClientLoginToOAuth2CookiePartHttpOnly
)) {
535 std::vector
<std::string
>::const_iterator iter
;
536 for (iter
= parts
.begin(); iter
!= parts
.end(); ++iter
) {
537 const std::string
& part
= *iter
;
539 part
, kClientLoginToOAuth2CookiePartCodePrefix
, false)) {
540 auth_code
->assign(part
.substr(
541 kClientLoginToOAuth2CookiePartCodePrefixLength
));
549 bool GaiaAuthFetcher::ParseListIdpSessionsResponse(const std::string
& data
,
550 std::string
* login_hint
) {
553 scoped_ptr
<base::Value
> value(base::JSONReader::Read(data
));
554 if (!value
.get() || value
->GetType() != base::Value::TYPE_DICTIONARY
)
557 base::DictionaryValue
* dict
=
558 static_cast<base::DictionaryValue
*>(value
.get());
560 base::ListValue
* sessionsList
;
561 if (!dict
->GetList("sessions", &sessionsList
))
564 // Find the first login_hint present in any session.
565 for (base::ListValue::iterator iter
= sessionsList
->begin();
566 iter
!= sessionsList
->end();
568 base::DictionaryValue
* sessionDictionary
;
569 if (!(*iter
)->GetAsDictionary(&sessionDictionary
))
572 if (sessionDictionary
->GetString("login_hint", login_hint
))
576 if (login_hint
->empty())
581 void GaiaAuthFetcher::StartClientLogin(
582 const std::string
& username
,
583 const std::string
& password
,
584 const char* const service
,
585 const std::string
& login_token
,
586 const std::string
& login_captcha
,
587 HostedAccountsSetting allow_hosted_accounts
) {
589 DCHECK(!fetch_pending_
) << "Tried to fetch two things at once!";
591 // This class is thread agnostic, so be sure to call this only on the
592 // same thread each time.
593 DVLOG(1) << "Starting new ClientLogin fetch for:" << username
;
595 // Must outlive fetcher_.
596 request_body_
= MakeClientLoginBody(username
,
602 allow_hosted_accounts
);
604 CreateGaiaFetcher(getter_
, request_body_
, std::string(),
605 client_login_gurl_
, kLoadFlagsIgnoreCookies
, this);
606 fetch_pending_
= true;
610 void GaiaAuthFetcher::StartIssueAuthToken(const std::string
& sid
,
611 const std::string
& lsid
,
612 const char* const service
) {
613 DCHECK(!fetch_pending_
) << "Tried to fetch two things at once!";
615 DVLOG(1) << "Starting IssueAuthToken for: " << service
;
616 requested_service_
= service
;
617 request_body_
= MakeIssueAuthTokenBody(sid
, lsid
, service
);
619 CreateGaiaFetcher(getter_
, request_body_
, std::string(),
620 issue_auth_token_gurl_
, kLoadFlagsIgnoreCookies
, this);
621 fetch_pending_
= true;
625 void GaiaAuthFetcher::StartLsoForOAuthLoginTokenExchange(
626 const std::string
& auth_token
) {
627 DCHECK(!fetch_pending_
) << "Tried to fetch two things at once!";
629 DVLOG(1) << "Starting OAuth login token exchange with auth_token";
630 request_body_
= MakeGetAuthCodeBody(false);
631 client_login_to_oauth2_gurl_
=
632 GaiaUrls::GetInstance()->client_login_to_oauth2_url();
634 fetcher_
= CreateGaiaFetcher(
635 getter_
, request_body_
, MakeGetAuthCodeHeader(auth_token
),
636 client_login_to_oauth2_gurl_
, kLoadFlagsIgnoreCookies
, this);
637 fetch_pending_
= true;
641 void GaiaAuthFetcher::StartRevokeOAuth2Token(const std::string
& auth_token
) {
642 DCHECK(!fetch_pending_
) << "Tried to fetch two things at once!";
644 DVLOG(1) << "Starting OAuth2 token revocation";
645 request_body_
= MakeRevokeTokenBody(auth_token
);
647 CreateGaiaFetcher(getter_
, request_body_
, std::string(),
648 oauth2_revoke_gurl_
, kLoadFlagsIgnoreCookies
, this);
649 fetch_pending_
= true;
653 void GaiaAuthFetcher::StartCookieForOAuthLoginTokenExchange(
654 const std::string
& session_index
) {
655 StartCookieForOAuthLoginTokenExchangeWithDeviceId(session_index
,
659 void GaiaAuthFetcher::StartCookieForOAuthLoginTokenExchangeWithDeviceId(
660 const std::string
& session_index
,
661 const std::string
& device_id
) {
662 DCHECK(!fetch_pending_
) << "Tried to fetch two things at once!";
664 DVLOG(1) << "Starting OAuth login token fetch with cookie jar";
665 request_body_
= MakeGetAuthCodeBody(!device_id
.empty());
667 client_login_to_oauth2_gurl_
=
668 GaiaUrls::GetInstance()->client_login_to_oauth2_url();
669 if (!session_index
.empty()) {
670 client_login_to_oauth2_gurl_
=
671 client_login_to_oauth2_gurl_
.Resolve("?authuser=" + session_index
);
674 std::string device_id_header
;
675 if (!device_id
.empty()) {
677 base::StringPrintf(kDeviceIdHeaderFormat
, device_id
.c_str());
681 CreateGaiaFetcher(getter_
, request_body_
, device_id_header
,
682 client_login_to_oauth2_gurl_
, net::LOAD_NORMAL
, this);
683 fetch_pending_
= true;
687 void GaiaAuthFetcher::StartAuthCodeForOAuth2TokenExchange(
688 const std::string
& auth_code
) {
689 StartAuthCodeForOAuth2TokenExchangeWithDeviceId(auth_code
, std::string());
692 void GaiaAuthFetcher::StartAuthCodeForOAuth2TokenExchangeWithDeviceId(
693 const std::string
& auth_code
,
694 const std::string
& device_id
) {
695 DCHECK(!fetch_pending_
) << "Tried to fetch two things at once!";
697 DVLOG(1) << "Starting OAuth token pair fetch";
698 request_body_
= MakeGetTokenPairBody(auth_code
, device_id
);
700 CreateGaiaFetcher(getter_
, request_body_
, std::string(),
701 oauth2_token_gurl_
, kLoadFlagsIgnoreCookies
, this);
702 fetch_pending_
= true;
706 void GaiaAuthFetcher::StartGetUserInfo(const std::string
& lsid
) {
707 DCHECK(!fetch_pending_
) << "Tried to fetch two things at once!";
709 DVLOG(1) << "Starting GetUserInfo for lsid=" << lsid
;
710 request_body_
= MakeGetUserInfoBody(lsid
);
712 CreateGaiaFetcher(getter_
, request_body_
, std::string(),
713 get_user_info_gurl_
, kLoadFlagsIgnoreCookies
, this);
714 fetch_pending_
= true;
718 void GaiaAuthFetcher::StartMergeSession(const std::string
& uber_token
,
719 const std::string
& external_cc_result
) {
720 DCHECK(!fetch_pending_
) << "Tried to fetch two things at once!";
722 DVLOG(1) << "Starting MergeSession with uber_token=" << uber_token
;
724 // The continue URL is a required parameter of the MergeSession API, but in
725 // this case we don't actually need or want to navigate to it. Setting it to
726 // an arbitrary Google URL.
728 // In order for the new session to be merged correctly, the server needs to
729 // know what sessions already exist in the browser. The fetcher needs to be
730 // created such that it sends the cookies with the request, which is
731 // different from all other requests the fetcher can make.
732 std::string
continue_url("http://www.google.com");
733 request_body_
= MakeMergeSessionBody(uber_token
, external_cc_result
,
734 continue_url
, source_
);
735 fetcher_
= CreateGaiaFetcher(getter_
, request_body_
, std::string(),
736 merge_session_gurl_
, net::LOAD_NORMAL
, this);
737 fetch_pending_
= true;
741 void GaiaAuthFetcher::StartTokenFetchForUberAuthExchange(
742 const std::string
& access_token
) {
743 DCHECK(!fetch_pending_
) << "Tried to fetch two things at once!";
745 DVLOG(1) << "Starting StartTokenFetchForUberAuthExchange with access_token="
747 std::string authentication_header
=
748 base::StringPrintf(kOAuthHeaderFormat
, access_token
.c_str());
749 fetcher_
= CreateGaiaFetcher(getter_
, std::string(), authentication_header
,
750 uberauth_token_gurl_
, net::LOAD_NORMAL
, this);
751 fetch_pending_
= true;
755 void GaiaAuthFetcher::StartOAuthLogin(const std::string
& access_token
,
756 const std::string
& service
) {
757 DCHECK(!fetch_pending_
) << "Tried to fetch two things at once!";
759 request_body_
= MakeOAuthLoginBody(service
, source_
);
760 std::string authentication_header
=
761 base::StringPrintf(kOAuth2BearerHeaderFormat
, access_token
.c_str());
762 fetcher_
= CreateGaiaFetcher(getter_
, request_body_
, authentication_header
,
763 oauth_login_gurl_
, net::LOAD_NORMAL
, this);
764 fetch_pending_
= true;
768 void GaiaAuthFetcher::StartListAccounts() {
769 DCHECK(!fetch_pending_
) << "Tried to fetch two things at once!";
771 fetcher_
= CreateGaiaFetcher(getter_
,
772 " ", // To force an HTTP POST.
773 "Origin: https://www.google.com",
774 list_accounts_gurl_
, net::LOAD_NORMAL
, this);
775 fetch_pending_
= true;
779 void GaiaAuthFetcher::StartGetCheckConnectionInfo() {
780 DCHECK(!fetch_pending_
) << "Tried to fetch two things at once!";
782 fetcher_
= CreateGaiaFetcher(getter_
, std::string(), std::string(),
783 get_check_connection_info_url_
,
784 kLoadFlagsIgnoreCookies
, this);
785 fetch_pending_
= true;
789 void GaiaAuthFetcher::StartListIDPSessions(const std::string
& scopes
,
790 const std::string
& domain
) {
791 DCHECK(!fetch_pending_
) << "Tried to fetch two things at once!";
793 request_body_
= MakeListIDPSessionsBody(scopes
, domain
);
794 fetcher_
= CreateGaiaFetcher(getter_
, request_body_
, std::string(),
795 oauth2_iframe_url_
, net::LOAD_NORMAL
, this);
796 requested_service_
= kListIdpServiceRequested
;
797 fetch_pending_
= true;
801 void GaiaAuthFetcher::StartGetTokenResponse(const std::string
& scopes
,
802 const std::string
& domain
,
803 const std::string
& login_hint
) {
804 DCHECK(!fetch_pending_
) << "Tried to fetch two things at once!";
806 request_body_
= MakeGetTokenResponseBody(scopes
, domain
, login_hint
);
807 fetcher_
= CreateGaiaFetcher(getter_
, request_body_
, std::string(),
808 oauth2_iframe_url_
, net::LOAD_NORMAL
, this);
810 requested_service_
= kGetTokenResponseRequested
;
811 fetch_pending_
= true;
816 GoogleServiceAuthError
GaiaAuthFetcher::GenerateAuthError(
817 const std::string
& data
,
818 const net::URLRequestStatus
& status
) {
819 if (!status
.is_success()) {
820 if (status
.status() == net::URLRequestStatus::CANCELED
) {
821 return GoogleServiceAuthError(GoogleServiceAuthError::REQUEST_CANCELED
);
823 DLOG(WARNING
) << "Could not reach Google Accounts servers: errno "
825 return GoogleServiceAuthError::FromConnectionError(status
.error());
828 if (IsSecondFactorSuccess(data
))
829 return GoogleServiceAuthError(GoogleServiceAuthError::TWO_FACTOR
);
831 if (IsWebLoginRequiredSuccess(data
))
832 return GoogleServiceAuthError(GoogleServiceAuthError::WEB_LOGIN_REQUIRED
);
836 std::string captcha_url
;
837 std::string captcha_token
;
838 ParseClientLoginFailure(data
, &error
, &url
, &captcha_url
, &captcha_token
);
839 DLOG(WARNING
) << "ClientLogin failed with " << error
;
841 if (error
== kCaptchaError
) {
842 return GoogleServiceAuthError::FromClientLoginCaptchaChallenge(
844 GURL(GaiaUrls::GetInstance()->captcha_base_url().Resolve(captcha_url
)),
847 if (error
== kAccountDeletedError
)
848 return GoogleServiceAuthError(GoogleServiceAuthError::ACCOUNT_DELETED
);
849 if (error
== kAccountDisabledError
)
850 return GoogleServiceAuthError(GoogleServiceAuthError::ACCOUNT_DISABLED
);
851 if (error
== kBadAuthenticationError
) {
852 return GoogleServiceAuthError(
853 GoogleServiceAuthError::INVALID_GAIA_CREDENTIALS
);
855 if (error
== kServiceUnavailableError
) {
856 return GoogleServiceAuthError(
857 GoogleServiceAuthError::SERVICE_UNAVAILABLE
);
860 DLOG(WARNING
) << "Incomprehensible response from Google Accounts servers.";
861 return GoogleServiceAuthError(GoogleServiceAuthError::SERVICE_UNAVAILABLE
);
864 void GaiaAuthFetcher::OnClientLoginFetched(const std::string
& data
,
865 const net::URLRequestStatus
& status
,
867 if (status
.is_success() && response_code
== net::HTTP_OK
) {
868 DVLOG(1) << "ClientLogin successful!";
872 ParseClientLoginResponse(data
, &sid
, &lsid
, &token
);
873 consumer_
->OnClientLoginSuccess(
874 GaiaAuthConsumer::ClientLoginResult(sid
, lsid
, token
, data
));
876 consumer_
->OnClientLoginFailure(GenerateAuthError(data
, status
));
880 void GaiaAuthFetcher::OnIssueAuthTokenFetched(
881 const std::string
& data
,
882 const net::URLRequestStatus
& status
,
884 if (status
.is_success() && response_code
== net::HTTP_OK
) {
885 // Only the bare token is returned in the body of this Gaia call
886 // without any padding.
887 consumer_
->OnIssueAuthTokenSuccess(requested_service_
, data
);
889 consumer_
->OnIssueAuthTokenFailure(requested_service_
,
890 GenerateAuthError(data
, status
));
894 void GaiaAuthFetcher::OnClientLoginToOAuth2Fetched(
895 const std::string
& data
,
896 const net::ResponseCookies
& cookies
,
897 const net::URLRequestStatus
& status
,
899 if (status
.is_success() && response_code
== net::HTTP_OK
) {
900 std::string auth_code
;
901 if (ParseClientLoginToOAuth2Response(cookies
, &auth_code
)) {
902 StartAuthCodeForOAuth2TokenExchange(auth_code
);
904 GoogleServiceAuthError
auth_error(
905 GoogleServiceAuthError::FromUnexpectedServiceResponse(
906 "ClientLogin response cookies didn't contain an auth code"));
907 consumer_
->OnClientOAuthFailure(auth_error
);
910 GoogleServiceAuthError
auth_error(GenerateAuthError(data
, status
));
911 consumer_
->OnClientOAuthFailure(auth_error
);
915 void GaiaAuthFetcher::OnOAuth2TokenPairFetched(
916 const std::string
& data
,
917 const net::URLRequestStatus
& status
,
919 std::string refresh_token
;
920 std::string access_token
;
921 int expires_in_secs
= 0;
923 bool success
= false;
924 if (status
.is_success() && response_code
== net::HTTP_OK
) {
925 success
= ExtractOAuth2TokenPairResponse(data
, &refresh_token
,
926 &access_token
, &expires_in_secs
);
930 consumer_
->OnClientOAuthSuccess(
931 GaiaAuthConsumer::ClientOAuthResult(refresh_token
, access_token
,
934 consumer_
->OnClientOAuthFailure(GenerateAuthError(data
, status
));
938 void GaiaAuthFetcher::OnOAuth2RevokeTokenFetched(
939 const std::string
& data
,
940 const net::URLRequestStatus
& status
,
942 consumer_
->OnOAuth2RevokeTokenCompleted();
945 void GaiaAuthFetcher::OnListAccountsFetched(const std::string
& data
,
946 const net::URLRequestStatus
& status
,
948 if (status
.is_success() && response_code
== net::HTTP_OK
) {
949 consumer_
->OnListAccountsSuccess(data
);
951 consumer_
->OnListAccountsFailure(GenerateAuthError(data
, status
));
955 void GaiaAuthFetcher::OnGetUserInfoFetched(
956 const std::string
& data
,
957 const net::URLRequestStatus
& status
,
959 if (status
.is_success() && response_code
== net::HTTP_OK
) {
960 base::StringPairs tokens
;
962 base::SplitStringIntoKeyValuePairs(data
, '=', '\n', &tokens
);
963 base::StringPairs::iterator i
;
964 for (i
= tokens
.begin(); i
!= tokens
.end(); ++i
) {
965 matches
[i
->first
] = i
->second
;
967 consumer_
->OnGetUserInfoSuccess(matches
);
969 consumer_
->OnGetUserInfoFailure(GenerateAuthError(data
, status
));
973 void GaiaAuthFetcher::OnMergeSessionFetched(const std::string
& data
,
974 const net::URLRequestStatus
& status
,
976 if (status
.is_success() && response_code
== net::HTTP_OK
) {
977 consumer_
->OnMergeSessionSuccess(data
);
979 consumer_
->OnMergeSessionFailure(GenerateAuthError(data
, status
));
983 void GaiaAuthFetcher::OnUberAuthTokenFetch(const std::string
& data
,
984 const net::URLRequestStatus
& status
,
986 if (status
.is_success() && response_code
== net::HTTP_OK
) {
987 consumer_
->OnUberAuthTokenSuccess(data
);
989 consumer_
->OnUberAuthTokenFailure(GenerateAuthError(data
, status
));
993 void GaiaAuthFetcher::OnOAuthLoginFetched(const std::string
& data
,
994 const net::URLRequestStatus
& status
,
996 if (status
.is_success() && response_code
== net::HTTP_OK
) {
997 DVLOG(1) << "ClientLogin successful!";
1001 ParseClientLoginResponse(data
, &sid
, &lsid
, &token
);
1002 consumer_
->OnClientLoginSuccess(
1003 GaiaAuthConsumer::ClientLoginResult(sid
, lsid
, token
, data
));
1005 consumer_
->OnClientLoginFailure(GenerateAuthError(data
, status
));
1009 void GaiaAuthFetcher::OnGetCheckConnectionInfoFetched(
1010 const std::string
& data
,
1011 const net::URLRequestStatus
& status
,
1012 int response_code
) {
1013 if (status
.is_success() && response_code
== net::HTTP_OK
) {
1014 consumer_
->OnGetCheckConnectionInfoSuccess(data
);
1016 consumer_
->OnGetCheckConnectionInfoError(GenerateAuthError(data
, status
));
1020 void GaiaAuthFetcher::OnListIdpSessionsFetched(
1021 const std::string
& data
,
1022 const net::URLRequestStatus
& status
,
1023 int response_code
) {
1024 if (status
.is_success() && response_code
== net::HTTP_OK
) {
1025 DVLOG(1) << "ListIdpSessions successful!";
1026 std::string login_hint
;
1027 if (ParseListIdpSessionsResponse(data
, &login_hint
)) {
1028 consumer_
->OnListIdpSessionsSuccess(login_hint
);
1030 GoogleServiceAuthError
auth_error(
1031 GoogleServiceAuthError::FromUnexpectedServiceResponse(
1032 "List Sessions response didn't contain a login_hint."));
1033 consumer_
->OnListIdpSessionsError(auth_error
);
1036 consumer_
->OnListIdpSessionsError(GenerateAuthError(data
, status
));
1040 void GaiaAuthFetcher::OnGetTokenResponseFetched(
1041 const std::string
& data
,
1042 const net::URLRequestStatus
& status
,
1043 int response_code
) {
1044 std::string access_token
;
1045 int expires_in_secs
= 0;
1046 bool success
= false;
1047 if (status
.is_success() && response_code
== net::HTTP_OK
) {
1048 DVLOG(1) << "GetTokenResponse successful!";
1049 success
= ExtractOAuth2TokenPairResponse(data
, NULL
,
1050 &access_token
, &expires_in_secs
);
1054 consumer_
->OnGetTokenResponseSuccess(
1055 GaiaAuthConsumer::ClientOAuthResult(std::string(), access_token
,
1058 consumer_
->OnGetTokenResponseError(GenerateAuthError(data
, status
));
1062 void GaiaAuthFetcher::OnURLFetchComplete(const net::URLFetcher
* source
) {
1063 fetch_pending_
= false;
1064 // Some of the GAIA requests perform redirects, which results in the final
1065 // URL of the fetcher not being the original URL requested. Therefore use
1066 // the original URL when determining which OnXXX function to call.
1067 const GURL
& url
= source
->GetOriginalURL();
1068 const net::URLRequestStatus
& status
= source
->GetStatus();
1069 int response_code
= source
->GetResponseCode();
1071 source
->GetResponseAsString(&data
);
1073 std::string headers
;
1074 if (source
->GetResponseHeaders())
1075 source
->GetResponseHeaders()->GetNormalizedHeaders(&headers
);
1076 DVLOG(2) << "Response " << url
.spec() << ", code = " << response_code
<< "\n"
1078 DVLOG(2) << "data: " << data
<< "\n";
1080 // Retrieve the response headers from the request. Must only be called after
1081 // the OnURLFetchComplete callback has run.
1082 if (url
== client_login_gurl_
) {
1083 OnClientLoginFetched(data
, status
, response_code
);
1084 } else if (url
== issue_auth_token_gurl_
) {
1085 OnIssueAuthTokenFetched(data
, status
, response_code
);
1086 } else if (url
== client_login_to_oauth2_gurl_
) {
1087 OnClientLoginToOAuth2Fetched(
1088 data
, source
->GetCookies(), status
, response_code
);
1089 } else if (url
== oauth2_token_gurl_
) {
1090 OnOAuth2TokenPairFetched(data
, status
, response_code
);
1091 } else if (url
== get_user_info_gurl_
) {
1092 OnGetUserInfoFetched(data
, status
, response_code
);
1093 } else if (url
== merge_session_gurl_
) {
1094 OnMergeSessionFetched(data
, status
, response_code
);
1095 } else if (url
== uberauth_token_gurl_
) {
1096 OnUberAuthTokenFetch(data
, status
, response_code
);
1097 } else if (url
== oauth_login_gurl_
) {
1098 OnOAuthLoginFetched(data
, status
, response_code
);
1099 } else if (url
== oauth2_revoke_gurl_
) {
1100 OnOAuth2RevokeTokenFetched(data
, status
, response_code
);
1101 } else if (url
== list_accounts_gurl_
) {
1102 OnListAccountsFetched(data
, status
, response_code
);
1103 } else if (url
== get_check_connection_info_url_
) {
1104 OnGetCheckConnectionInfoFetched(data
, status
, response_code
);
1105 } else if (url
== oauth2_iframe_url_
) {
1106 if (requested_service_
== kListIdpServiceRequested
)
1107 OnListIdpSessionsFetched(data
, status
, response_code
);
1108 else if (requested_service_
== kGetTokenResponseRequested
)
1109 OnGetTokenResponseFetched(data
, status
, response_code
);
1118 bool GaiaAuthFetcher::IsSecondFactorSuccess(
1119 const std::string
& alleged_error
) {
1120 return alleged_error
.find(kSecondFactor
) !=
1125 bool GaiaAuthFetcher::IsWebLoginRequiredSuccess(
1126 const std::string
& alleged_error
) {
1127 return alleged_error
.find(kWebLoginRequired
) !=