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 (base::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::kClientLoginToOAuth2URLFormat
[] =
106 "?scope=%s&client_id=%s";
108 const char GaiaAuthFetcher::kOAuth2CodeToTokenPairBodyFormat
[] =
110 "grant_type=authorization_code&"
115 const char GaiaAuthFetcher::kOAuth2CodeToTokenPairDeviceIdParam
[] =
116 "device_id=%s&device_type=chrome";
118 const char GaiaAuthFetcher::kOAuth2RevokeTokenBodyFormat
[] =
121 const char GaiaAuthFetcher::kGetUserInfoFormat
[] =
124 const char GaiaAuthFetcher::kMergeSessionFormat
[] =
129 const char GaiaAuthFetcher::kUberAuthTokenURLFormat
[] =
133 const char GaiaAuthFetcher::kOAuthLoginFormat
[] = "service=%s&source=%s";
136 const char GaiaAuthFetcher::kAccountDeletedError
[] = "AccountDeleted";
138 const char GaiaAuthFetcher::kAccountDisabledError
[] = "AccountDisabled";
140 const char GaiaAuthFetcher::kBadAuthenticationError
[] = "BadAuthentication";
142 const char GaiaAuthFetcher::kCaptchaError
[] = "CaptchaRequired";
144 const char GaiaAuthFetcher::kServiceUnavailableError
[] =
145 "ServiceUnavailable";
147 const char GaiaAuthFetcher::kErrorParam
[] = "Error";
149 const char GaiaAuthFetcher::kErrorUrlParam
[] = "Url";
151 const char GaiaAuthFetcher::kCaptchaUrlParam
[] = "CaptchaUrl";
153 const char GaiaAuthFetcher::kCaptchaTokenParam
[] = "CaptchaToken";
156 const char GaiaAuthFetcher::kCookiePersistence
[] = "true";
158 // TODO(johnnyg): When hosted accounts are supported by sync,
159 // we can always use "HOSTED_OR_GOOGLE"
160 const char GaiaAuthFetcher::kAccountTypeHostedOrGoogle
[] =
162 const char GaiaAuthFetcher::kAccountTypeGoogle
[] =
166 const char GaiaAuthFetcher::kSecondFactor
[] = "Info=InvalidSecondFactor";
168 const char GaiaAuthFetcher::kWebLoginRequired
[] = "Info=WebLoginRequired";
171 const char GaiaAuthFetcher::kAuthHeaderFormat
[] =
172 "Authorization: GoogleLogin auth=%s";
174 const char GaiaAuthFetcher::kOAuthHeaderFormat
[] = "Authorization: OAuth %s";
176 const char GaiaAuthFetcher::kOAuth2BearerHeaderFormat
[] =
177 "Authorization: Bearer %s";
179 const char GaiaAuthFetcher::kDeviceIdHeaderFormat
[] = "X-Device-ID: %s";
181 const char GaiaAuthFetcher::kClientLoginToOAuth2CookiePartSecure
[] = "secure";
183 const char GaiaAuthFetcher::kClientLoginToOAuth2CookiePartHttpOnly
[] =
186 const char GaiaAuthFetcher::kClientLoginToOAuth2CookiePartCodePrefix
[] =
189 const int GaiaAuthFetcher::kClientLoginToOAuth2CookiePartCodePrefixLength
=
190 arraysize(GaiaAuthFetcher::kClientLoginToOAuth2CookiePartCodePrefix
) - 1;
192 GaiaAuthFetcher::GaiaAuthFetcher(GaiaAuthConsumer
* consumer
,
193 const std::string
& source
,
194 net::URLRequestContextGetter
* getter
)
195 : consumer_(consumer
),
198 client_login_gurl_(GaiaUrls::GetInstance()->client_login_url()),
199 issue_auth_token_gurl_(GaiaUrls::GetInstance()->issue_auth_token_url()),
200 oauth2_token_gurl_(GaiaUrls::GetInstance()->oauth2_token_url()),
201 oauth2_revoke_gurl_(GaiaUrls::GetInstance()->oauth2_revoke_url()),
202 get_user_info_gurl_(GaiaUrls::GetInstance()->get_user_info_url()),
203 merge_session_gurl_(GaiaUrls::GetInstance()->merge_session_url()),
204 uberauth_token_gurl_(GaiaUrls::GetInstance()->oauth1_login_url().Resolve(
205 base::StringPrintf(kUberAuthTokenURLFormat
, source
.c_str()))),
206 oauth_login_gurl_(GaiaUrls::GetInstance()->oauth1_login_url()),
208 GaiaUrls::GetInstance()->ListAccountsURLWithSource(source
)),
209 logout_gurl_(GaiaUrls::GetInstance()->LogOutURLWithSource(source
)),
210 get_check_connection_info_url_(
211 GaiaUrls::GetInstance()->GetCheckConnectionInfoURLWithSource(source
)),
212 oauth2_iframe_url_(GaiaUrls::GetInstance()->oauth2_iframe_url()),
213 client_login_to_oauth2_gurl_(
214 GaiaUrls::GetInstance()->client_login_to_oauth2_url()),
215 fetch_pending_(false) {
218 GaiaAuthFetcher::~GaiaAuthFetcher() {}
220 bool GaiaAuthFetcher::HasPendingFetch() {
221 return fetch_pending_
;
224 void GaiaAuthFetcher::SetPendingFetch(bool pending_fetch
) {
225 fetch_pending_
= pending_fetch
;
228 void GaiaAuthFetcher::CancelRequest() {
230 fetch_pending_
= false;
233 void GaiaAuthFetcher::CreateAndStartGaiaFetcher(const std::string
& body
,
234 const std::string
& headers
,
235 const GURL
& gaia_gurl
,
237 DCHECK(!fetch_pending_
) << "Tried to fetch two things at once!";
238 fetcher_
= net::URLFetcher::Create(
239 0, gaia_gurl
, body
.empty() ? net::URLFetcher::GET
: net::URLFetcher::POST
,
241 fetcher_
->SetRequestContext(getter_
);
242 fetcher_
->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 fetcher_
->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 fetcher_
->SetAutomaticallyRetryOnNetworkChanges(3);
261 if (!headers
.empty())
262 fetcher_
->SetExtraRequestHeaders(headers
);
264 fetch_pending_
= true;
269 std::string
GaiaAuthFetcher::MakeClientLoginBody(
270 const std::string
& username
,
271 const std::string
& password
,
272 const std::string
& source
,
274 const std::string
& login_token
,
275 const std::string
& login_captcha
,
276 HostedAccountsSetting allow_hosted_accounts
) {
277 std::string encoded_username
= net::EscapeUrlEncodedData(username
, true);
278 std::string encoded_password
= net::EscapeUrlEncodedData(password
, true);
279 std::string encoded_login_token
= net::EscapeUrlEncodedData(login_token
,
281 std::string encoded_login_captcha
= net::EscapeUrlEncodedData(login_captcha
,
284 const char* account_type
= allow_hosted_accounts
== HostedAccountsAllowed
?
285 kAccountTypeHostedOrGoogle
:
288 if (login_token
.empty() || login_captcha
.empty()) {
289 return base::StringPrintf(kClientLoginFormat
,
290 encoded_username
.c_str(),
291 encoded_password
.c_str(),
298 return base::StringPrintf(kClientLoginCaptchaFormat
,
299 encoded_username
.c_str(),
300 encoded_password
.c_str(),
305 encoded_login_token
.c_str(),
306 encoded_login_captcha
.c_str());
310 std::string
GaiaAuthFetcher::MakeIssueAuthTokenBody(
311 const std::string
& sid
,
312 const std::string
& lsid
,
313 const char* const service
) {
314 std::string encoded_sid
= net::EscapeUrlEncodedData(sid
, true);
315 std::string encoded_lsid
= net::EscapeUrlEncodedData(lsid
, true);
317 // All tokens should be session tokens except the gaia auth token.
319 if (!strcmp(service
, GaiaConstants::kGaiaService
))
322 return base::StringPrintf(kIssueAuthTokenFormat
,
324 encoded_lsid
.c_str(),
326 session
? "true" : "false");
330 std::string
GaiaAuthFetcher::MakeGetTokenPairBody(
331 const std::string
& auth_code
,
332 const std::string
& device_id
) {
333 std::string encoded_scope
= net::EscapeUrlEncodedData(
334 GaiaConstants::kOAuth1LoginScope
, true);
335 std::string encoded_client_id
= net::EscapeUrlEncodedData(
336 GaiaUrls::GetInstance()->oauth2_chrome_client_id(), true);
337 std::string encoded_client_secret
= net::EscapeUrlEncodedData(
338 GaiaUrls::GetInstance()->oauth2_chrome_client_secret(), true);
339 std::string encoded_auth_code
= net::EscapeUrlEncodedData(auth_code
, true);
340 std::string body
= base::StringPrintf(
341 kOAuth2CodeToTokenPairBodyFormat
, encoded_scope
.c_str(),
342 encoded_client_id
.c_str(), encoded_client_secret
.c_str(),
343 encoded_auth_code
.c_str());
344 if (!device_id
.empty()) {
345 body
+= "&" + base::StringPrintf(kOAuth2CodeToTokenPairDeviceIdParam
,
352 std::string
GaiaAuthFetcher::MakeRevokeTokenBody(
353 const std::string
& auth_token
) {
354 return base::StringPrintf(kOAuth2RevokeTokenBodyFormat
, auth_token
.c_str());
358 std::string
GaiaAuthFetcher::MakeGetUserInfoBody(const std::string
& lsid
) {
359 std::string encoded_lsid
= net::EscapeUrlEncodedData(lsid
, true);
360 return base::StringPrintf(kGetUserInfoFormat
, encoded_lsid
.c_str());
364 std::string
GaiaAuthFetcher::MakeMergeSessionBody(
365 const std::string
& auth_token
,
366 const std::string
& external_cc_result
,
367 const std::string
& continue_url
,
368 const std::string
& source
) {
369 std::string encoded_auth_token
= net::EscapeUrlEncodedData(auth_token
, true);
370 std::string encoded_continue_url
= net::EscapeUrlEncodedData(continue_url
,
372 std::string encoded_source
= net::EscapeUrlEncodedData(source
, true);
373 std::string result
= base::StringPrintf(kMergeSessionFormat
,
374 encoded_auth_token
.c_str(),
375 encoded_continue_url
.c_str(),
376 encoded_source
.c_str());
377 if (!external_cc_result
.empty()) {
378 base::StringAppendF(&result
, "&externalCcResult=%s",
379 net::EscapeUrlEncodedData(
380 external_cc_result
, true).c_str());
387 std::string
GaiaAuthFetcher::MakeGetAuthCodeHeader(
388 const std::string
& auth_token
) {
389 return base::StringPrintf(kAuthHeaderFormat
, auth_token
.c_str());
392 // Helper method that extracts tokens from a successful reply.
394 void GaiaAuthFetcher::ParseClientLoginResponse(const std::string
& data
,
397 std::string
* token
) {
404 base::StringPairs tokens
;
405 base::SplitStringIntoKeyValuePairs(data
, '=', '\n', &tokens
);
406 for (base::StringPairs::iterator i
= tokens
.begin();
407 i
!= tokens
.end(); ++i
) {
408 if (i
->first
== "SID") {
409 sid
->assign(i
->second
);
410 } else if (i
->first
== "LSID") {
411 lsid
->assign(i
->second
);
412 } else if (i
->first
== "Auth") {
413 token
->assign(i
->second
);
416 // If this was a request for uberauth token, then that's all we've got in
418 if (sid
->empty() && lsid
->empty() && token
->empty())
423 std::string
GaiaAuthFetcher::MakeOAuthLoginBody(const std::string
& service
,
424 const std::string
& source
) {
425 std::string encoded_service
= net::EscapeUrlEncodedData(service
, true);
426 std::string encoded_source
= net::EscapeUrlEncodedData(source
, true);
427 return base::StringPrintf(kOAuthLoginFormat
,
428 encoded_service
.c_str(),
429 encoded_source
.c_str());
433 std::string
GaiaAuthFetcher::MakeListIDPSessionsBody(
434 const std::string
& scopes
,
435 const std::string
& domain
) {
436 static const char getTokenResponseBodyFormat
[] =
437 "action=listSessions&"
441 std::string encoded_client_id
= net::EscapeUrlEncodedData(
442 GaiaUrls::GetInstance()->oauth2_chrome_client_id(), true);
443 return base::StringPrintf(getTokenResponseBodyFormat
,
444 encoded_client_id
.c_str(),
449 std::string
GaiaAuthFetcher::MakeGetTokenResponseBody(
450 const std::string
& scopes
,
451 const std::string
& domain
,
452 const std::string
& login_hint
) {
453 static const char getTokenResponseBodyFormat
[] =
458 "response_type=token&"
460 std::string encoded_client_id
= net::EscapeUrlEncodedData(
461 GaiaUrls::GetInstance()->oauth2_chrome_client_id(), true);
462 return base::StringPrintf(getTokenResponseBodyFormat
,
463 encoded_client_id
.c_str(),
470 void GaiaAuthFetcher::ParseClientLoginFailure(const std::string
& data
,
472 std::string
* error_url
,
473 std::string
* captcha_url
,
474 std::string
* captcha_token
) {
479 base::StringPairs tokens
;
480 base::SplitStringIntoKeyValuePairs(data
, '=', '\n', &tokens
);
481 for (base::StringPairs::iterator i
= tokens
.begin();
482 i
!= tokens
.end(); ++i
) {
483 if (i
->first
== kErrorParam
) {
484 error
->assign(i
->second
);
485 } else if (i
->first
== kErrorUrlParam
) {
486 error_url
->assign(i
->second
);
487 } else if (i
->first
== kCaptchaUrlParam
) {
488 captcha_url
->assign(i
->second
);
489 } else if (i
->first
== kCaptchaTokenParam
) {
490 captcha_token
->assign(i
->second
);
496 bool GaiaAuthFetcher::ParseClientLoginToOAuth2Response(
497 const net::ResponseCookies
& cookies
,
498 std::string
* auth_code
) {
500 net::ResponseCookies::const_iterator iter
;
501 for (iter
= cookies
.begin(); iter
!= cookies
.end(); ++iter
) {
502 if (ParseClientLoginToOAuth2Cookie(*iter
, auth_code
))
509 bool GaiaAuthFetcher::ParseClientLoginToOAuth2Cookie(const std::string
& cookie
,
510 std::string
* auth_code
) {
511 std::vector
<std::string
> parts
;
512 base::SplitString(cookie
, ';', &parts
);
513 // Per documentation, the cookie should have Secure and HttpOnly.
514 if (!CookiePartsContains(parts
, kClientLoginToOAuth2CookiePartSecure
) ||
515 !CookiePartsContains(parts
, kClientLoginToOAuth2CookiePartHttpOnly
)) {
519 std::vector
<std::string
>::const_iterator iter
;
520 for (iter
= parts
.begin(); iter
!= parts
.end(); ++iter
) {
521 const std::string
& part
= *iter
;
522 if (base::StartsWithASCII(part
, kClientLoginToOAuth2CookiePartCodePrefix
,
524 auth_code
->assign(part
.substr(
525 kClientLoginToOAuth2CookiePartCodePrefixLength
));
533 bool GaiaAuthFetcher::ParseListIdpSessionsResponse(const std::string
& data
,
534 std::string
* login_hint
) {
537 scoped_ptr
<base::Value
> value
= base::JSONReader::Read(data
);
538 if (!value
.get() || value
->GetType() != base::Value::TYPE_DICTIONARY
)
541 base::DictionaryValue
* dict
=
542 static_cast<base::DictionaryValue
*>(value
.get());
544 base::ListValue
* sessionsList
;
545 if (!dict
->GetList("sessions", &sessionsList
))
548 // Find the first login_hint present in any session.
549 for (base::ListValue::iterator iter
= sessionsList
->begin();
550 iter
!= sessionsList
->end();
552 base::DictionaryValue
* sessionDictionary
;
553 if (!(*iter
)->GetAsDictionary(&sessionDictionary
))
556 if (sessionDictionary
->GetString("login_hint", login_hint
))
560 if (login_hint
->empty())
565 void GaiaAuthFetcher::StartClientLogin(
566 const std::string
& username
,
567 const std::string
& password
,
568 const char* const service
,
569 const std::string
& login_token
,
570 const std::string
& login_captcha
,
571 HostedAccountsSetting allow_hosted_accounts
) {
573 DCHECK(!fetch_pending_
) << "Tried to fetch two things at once!";
575 // This class is thread agnostic, so be sure to call this only on the
576 // same thread each time.
577 DVLOG(1) << "Starting new ClientLogin fetch for:" << username
;
579 // Must outlive fetcher_.
580 request_body_
= MakeClientLoginBody(username
,
586 allow_hosted_accounts
);
587 CreateAndStartGaiaFetcher(request_body_
, std::string(), client_login_gurl_
,
588 kLoadFlagsIgnoreCookies
);
591 void GaiaAuthFetcher::StartIssueAuthToken(const std::string
& sid
,
592 const std::string
& lsid
,
593 const char* const service
) {
594 DCHECK(!fetch_pending_
) << "Tried to fetch two things at once!";
596 DVLOG(1) << "Starting IssueAuthToken for: " << service
;
597 requested_service_
= service
;
598 request_body_
= MakeIssueAuthTokenBody(sid
, lsid
, service
);
599 CreateAndStartGaiaFetcher(request_body_
, std::string(),
600 issue_auth_token_gurl_
, kLoadFlagsIgnoreCookies
);
603 void GaiaAuthFetcher::StartRevokeOAuth2Token(const std::string
& auth_token
) {
604 DCHECK(!fetch_pending_
) << "Tried to fetch two things at once!";
606 DVLOG(1) << "Starting OAuth2 token revocation";
607 request_body_
= MakeRevokeTokenBody(auth_token
);
608 CreateAndStartGaiaFetcher(request_body_
, std::string(), oauth2_revoke_gurl_
,
609 kLoadFlagsIgnoreCookies
);
612 void GaiaAuthFetcher::StartCookieForOAuthLoginTokenExchange(
613 const std::string
& session_index
) {
614 StartCookieForOAuthLoginTokenExchangeWithDeviceId(session_index
,
618 void GaiaAuthFetcher::StartCookieForOAuthLoginTokenExchangeWithDeviceId(
619 const std::string
& session_index
,
620 const std::string
& device_id
) {
621 DCHECK(!fetch_pending_
) << "Tried to fetch two things at once!";
623 DVLOG(1) << "Starting OAuth login token fetch with cookie jar";
625 std::string encoded_scope
= net::EscapeUrlEncodedData(
626 GaiaConstants::kOAuth1LoginScope
, true);
627 std::string encoded_client_id
= net::EscapeUrlEncodedData(
628 GaiaUrls::GetInstance()->oauth2_chrome_client_id(), true);
629 std::string query_string
=
630 base::StringPrintf(kClientLoginToOAuth2URLFormat
, encoded_scope
.c_str(),
631 encoded_client_id
.c_str());
632 if (!device_id
.empty())
633 query_string
+= "&device_type=chrome";
634 if (!session_index
.empty())
635 query_string
+= "&authuser=" + session_index
;
637 std::string device_id_header
;
638 if (!device_id
.empty()) {
640 base::StringPrintf(kDeviceIdHeaderFormat
, device_id
.c_str());
643 CreateAndStartGaiaFetcher(std::string(), device_id_header
,
644 client_login_to_oauth2_gurl_
.Resolve(query_string
),
648 void GaiaAuthFetcher::StartAuthCodeForOAuth2TokenExchange(
649 const std::string
& auth_code
) {
650 StartAuthCodeForOAuth2TokenExchangeWithDeviceId(auth_code
, std::string());
653 void GaiaAuthFetcher::StartAuthCodeForOAuth2TokenExchangeWithDeviceId(
654 const std::string
& auth_code
,
655 const std::string
& device_id
) {
656 DCHECK(!fetch_pending_
) << "Tried to fetch two things at once!";
658 DVLOG(1) << "Starting OAuth token pair fetch";
659 request_body_
= MakeGetTokenPairBody(auth_code
, device_id
);
660 CreateAndStartGaiaFetcher(request_body_
, std::string(), oauth2_token_gurl_
,
661 kLoadFlagsIgnoreCookies
);
664 void GaiaAuthFetcher::StartGetUserInfo(const std::string
& lsid
) {
665 DCHECK(!fetch_pending_
) << "Tried to fetch two things at once!";
667 DVLOG(1) << "Starting GetUserInfo for lsid=" << lsid
;
668 request_body_
= MakeGetUserInfoBody(lsid
);
669 CreateAndStartGaiaFetcher(request_body_
, std::string(), get_user_info_gurl_
,
670 kLoadFlagsIgnoreCookies
);
673 void GaiaAuthFetcher::StartMergeSession(const std::string
& uber_token
,
674 const std::string
& external_cc_result
) {
675 DCHECK(!fetch_pending_
) << "Tried to fetch two things at once!";
677 DVLOG(1) << "Starting MergeSession with uber_token=" << uber_token
;
679 // The continue URL is a required parameter of the MergeSession API, but in
680 // this case we don't actually need or want to navigate to it. Setting it to
681 // an arbitrary Google URL.
683 // In order for the new session to be merged correctly, the server needs to
684 // know what sessions already exist in the browser. The fetcher needs to be
685 // created such that it sends the cookies with the request, which is
686 // different from all other requests the fetcher can make.
687 std::string
continue_url("http://www.google.com");
688 request_body_
= MakeMergeSessionBody(uber_token
, external_cc_result
,
689 continue_url
, source_
);
690 CreateAndStartGaiaFetcher(request_body_
, std::string(), merge_session_gurl_
,
694 void GaiaAuthFetcher::StartTokenFetchForUberAuthExchange(
695 const std::string
& access_token
) {
696 DCHECK(!fetch_pending_
) << "Tried to fetch two things at once!";
698 DVLOG(1) << "Starting StartTokenFetchForUberAuthExchange with access_token="
700 std::string authentication_header
=
701 base::StringPrintf(kOAuthHeaderFormat
, access_token
.c_str());
702 CreateAndStartGaiaFetcher(std::string(), authentication_header
,
703 uberauth_token_gurl_
, net::LOAD_NORMAL
);
706 void GaiaAuthFetcher::StartOAuthLogin(const std::string
& access_token
,
707 const std::string
& service
) {
708 DCHECK(!fetch_pending_
) << "Tried to fetch two things at once!";
710 request_body_
= MakeOAuthLoginBody(service
, source_
);
711 std::string authentication_header
=
712 base::StringPrintf(kOAuth2BearerHeaderFormat
, access_token
.c_str());
713 CreateAndStartGaiaFetcher(request_body_
, authentication_header
,
714 oauth_login_gurl_
, net::LOAD_NORMAL
);
717 void GaiaAuthFetcher::StartListAccounts() {
718 DCHECK(!fetch_pending_
) << "Tried to fetch two things at once!";
720 CreateAndStartGaiaFetcher(" ", // To force an HTTP POST.
721 "Origin: https://www.google.com",
722 list_accounts_gurl_
, net::LOAD_NORMAL
);
725 void GaiaAuthFetcher::StartLogOut() {
726 DCHECK(!fetch_pending_
) << "Tried to fetch two things at once!";
728 CreateAndStartGaiaFetcher(std::string(), std::string(), logout_gurl_
,
732 void GaiaAuthFetcher::StartGetCheckConnectionInfo() {
733 DCHECK(!fetch_pending_
) << "Tried to fetch two things at once!";
735 CreateAndStartGaiaFetcher(std::string(), std::string(),
736 get_check_connection_info_url_
,
737 kLoadFlagsIgnoreCookies
);
740 void GaiaAuthFetcher::StartListIDPSessions(const std::string
& scopes
,
741 const std::string
& domain
) {
742 DCHECK(!fetch_pending_
) << "Tried to fetch two things at once!";
744 request_body_
= MakeListIDPSessionsBody(scopes
, domain
);
745 requested_service_
= kListIdpServiceRequested
;
746 CreateAndStartGaiaFetcher(request_body_
, std::string(), oauth2_iframe_url_
,
750 void GaiaAuthFetcher::StartGetTokenResponse(const std::string
& scopes
,
751 const std::string
& domain
,
752 const std::string
& login_hint
) {
753 DCHECK(!fetch_pending_
) << "Tried to fetch two things at once!";
755 request_body_
= MakeGetTokenResponseBody(scopes
, domain
, login_hint
);
756 requested_service_
= kGetTokenResponseRequested
;
757 CreateAndStartGaiaFetcher(request_body_
, std::string(), oauth2_iframe_url_
,
762 GoogleServiceAuthError
GaiaAuthFetcher::GenerateAuthError(
763 const std::string
& data
,
764 const net::URLRequestStatus
& status
) {
765 if (!status
.is_success()) {
766 if (status
.status() == net::URLRequestStatus::CANCELED
) {
767 return GoogleServiceAuthError(GoogleServiceAuthError::REQUEST_CANCELED
);
769 DLOG(WARNING
) << "Could not reach Google Accounts servers: errno "
771 return GoogleServiceAuthError::FromConnectionError(status
.error());
774 if (IsSecondFactorSuccess(data
))
775 return GoogleServiceAuthError(GoogleServiceAuthError::TWO_FACTOR
);
777 if (IsWebLoginRequiredSuccess(data
))
778 return GoogleServiceAuthError(GoogleServiceAuthError::WEB_LOGIN_REQUIRED
);
782 std::string captcha_url
;
783 std::string captcha_token
;
784 ParseClientLoginFailure(data
, &error
, &url
, &captcha_url
, &captcha_token
);
785 DLOG(WARNING
) << "ClientLogin failed with " << error
;
787 if (error
== kCaptchaError
) {
788 return GoogleServiceAuthError::FromClientLoginCaptchaChallenge(
790 GURL(GaiaUrls::GetInstance()->captcha_base_url().Resolve(captcha_url
)),
793 if (error
== kAccountDeletedError
)
794 return GoogleServiceAuthError(GoogleServiceAuthError::ACCOUNT_DELETED
);
795 if (error
== kAccountDisabledError
)
796 return GoogleServiceAuthError(GoogleServiceAuthError::ACCOUNT_DISABLED
);
797 if (error
== kBadAuthenticationError
) {
798 return GoogleServiceAuthError(
799 GoogleServiceAuthError::INVALID_GAIA_CREDENTIALS
);
801 if (error
== kServiceUnavailableError
) {
802 return GoogleServiceAuthError(
803 GoogleServiceAuthError::SERVICE_UNAVAILABLE
);
806 DLOG(WARNING
) << "Incomprehensible response from Google Accounts servers.";
807 return GoogleServiceAuthError(GoogleServiceAuthError::SERVICE_UNAVAILABLE
);
810 void GaiaAuthFetcher::OnClientLoginFetched(const std::string
& data
,
811 const net::URLRequestStatus
& status
,
813 if (status
.is_success() && response_code
== net::HTTP_OK
) {
814 DVLOG(1) << "ClientLogin successful!";
818 ParseClientLoginResponse(data
, &sid
, &lsid
, &token
);
819 consumer_
->OnClientLoginSuccess(
820 GaiaAuthConsumer::ClientLoginResult(sid
, lsid
, token
, data
));
822 consumer_
->OnClientLoginFailure(GenerateAuthError(data
, status
));
826 void GaiaAuthFetcher::OnIssueAuthTokenFetched(
827 const std::string
& data
,
828 const net::URLRequestStatus
& status
,
830 if (status
.is_success() && response_code
== net::HTTP_OK
) {
831 // Only the bare token is returned in the body of this Gaia call
832 // without any padding.
833 consumer_
->OnIssueAuthTokenSuccess(requested_service_
, data
);
835 consumer_
->OnIssueAuthTokenFailure(requested_service_
,
836 GenerateAuthError(data
, status
));
840 void GaiaAuthFetcher::OnClientLoginToOAuth2Fetched(
841 const std::string
& data
,
842 const net::ResponseCookies
& cookies
,
843 const net::URLRequestStatus
& status
,
845 if (status
.is_success() && response_code
== net::HTTP_OK
) {
846 std::string auth_code
;
847 if (ParseClientLoginToOAuth2Response(cookies
, &auth_code
)) {
848 StartAuthCodeForOAuth2TokenExchange(auth_code
);
850 GoogleServiceAuthError
auth_error(
851 GoogleServiceAuthError::FromUnexpectedServiceResponse(
852 "ClientLogin response cookies didn't contain an auth code"));
853 consumer_
->OnClientOAuthFailure(auth_error
);
856 GoogleServiceAuthError
auth_error(GenerateAuthError(data
, status
));
857 consumer_
->OnClientOAuthFailure(auth_error
);
861 void GaiaAuthFetcher::OnOAuth2TokenPairFetched(
862 const std::string
& data
,
863 const net::URLRequestStatus
& status
,
865 std::string refresh_token
;
866 std::string access_token
;
867 int expires_in_secs
= 0;
869 bool success
= false;
870 if (status
.is_success() && response_code
== net::HTTP_OK
) {
871 success
= ExtractOAuth2TokenPairResponse(data
, &refresh_token
,
872 &access_token
, &expires_in_secs
);
876 consumer_
->OnClientOAuthSuccess(
877 GaiaAuthConsumer::ClientOAuthResult(refresh_token
, access_token
,
880 consumer_
->OnClientOAuthFailure(GenerateAuthError(data
, status
));
884 void GaiaAuthFetcher::OnOAuth2RevokeTokenFetched(
885 const std::string
& data
,
886 const net::URLRequestStatus
& status
,
888 consumer_
->OnOAuth2RevokeTokenCompleted();
891 void GaiaAuthFetcher::OnListAccountsFetched(const std::string
& data
,
892 const net::URLRequestStatus
& status
,
894 if (status
.is_success() && response_code
== net::HTTP_OK
) {
895 consumer_
->OnListAccountsSuccess(data
);
897 consumer_
->OnListAccountsFailure(GenerateAuthError(data
, status
));
901 void GaiaAuthFetcher::OnLogOutFetched(const std::string
& data
,
902 const net::URLRequestStatus
& status
,
904 if (status
.is_success() && response_code
== net::HTTP_OK
) {
905 consumer_
->OnLogOutSuccess();
907 consumer_
->OnLogOutFailure(GenerateAuthError(data
, status
));
911 void GaiaAuthFetcher::OnGetUserInfoFetched(
912 const std::string
& data
,
913 const net::URLRequestStatus
& status
,
915 if (status
.is_success() && response_code
== net::HTTP_OK
) {
916 base::StringPairs tokens
;
918 base::SplitStringIntoKeyValuePairs(data
, '=', '\n', &tokens
);
919 base::StringPairs::iterator i
;
920 for (i
= tokens
.begin(); i
!= tokens
.end(); ++i
) {
921 matches
[i
->first
] = i
->second
;
923 consumer_
->OnGetUserInfoSuccess(matches
);
925 consumer_
->OnGetUserInfoFailure(GenerateAuthError(data
, status
));
929 void GaiaAuthFetcher::OnMergeSessionFetched(const std::string
& data
,
930 const net::URLRequestStatus
& status
,
932 if (status
.is_success() && response_code
== net::HTTP_OK
) {
933 consumer_
->OnMergeSessionSuccess(data
);
935 consumer_
->OnMergeSessionFailure(GenerateAuthError(data
, status
));
939 void GaiaAuthFetcher::OnUberAuthTokenFetch(const std::string
& data
,
940 const net::URLRequestStatus
& status
,
942 if (status
.is_success() && response_code
== net::HTTP_OK
) {
943 consumer_
->OnUberAuthTokenSuccess(data
);
945 consumer_
->OnUberAuthTokenFailure(GenerateAuthError(data
, status
));
949 void GaiaAuthFetcher::OnOAuthLoginFetched(const std::string
& data
,
950 const net::URLRequestStatus
& status
,
952 if (status
.is_success() && response_code
== net::HTTP_OK
) {
953 DVLOG(1) << "ClientLogin successful!";
957 ParseClientLoginResponse(data
, &sid
, &lsid
, &token
);
958 consumer_
->OnClientLoginSuccess(
959 GaiaAuthConsumer::ClientLoginResult(sid
, lsid
, token
, data
));
961 consumer_
->OnClientLoginFailure(GenerateAuthError(data
, status
));
965 void GaiaAuthFetcher::OnGetCheckConnectionInfoFetched(
966 const std::string
& data
,
967 const net::URLRequestStatus
& status
,
969 if (status
.is_success() && response_code
== net::HTTP_OK
) {
970 consumer_
->OnGetCheckConnectionInfoSuccess(data
);
972 consumer_
->OnGetCheckConnectionInfoError(GenerateAuthError(data
, status
));
976 void GaiaAuthFetcher::OnListIdpSessionsFetched(
977 const std::string
& data
,
978 const net::URLRequestStatus
& status
,
980 if (status
.is_success() && response_code
== net::HTTP_OK
) {
981 DVLOG(1) << "ListIdpSessions successful!";
982 std::string login_hint
;
983 if (ParseListIdpSessionsResponse(data
, &login_hint
)) {
984 consumer_
->OnListIdpSessionsSuccess(login_hint
);
986 GoogleServiceAuthError
auth_error(
987 GoogleServiceAuthError::FromUnexpectedServiceResponse(
988 "List Sessions response didn't contain a login_hint."));
989 consumer_
->OnListIdpSessionsError(auth_error
);
992 consumer_
->OnListIdpSessionsError(GenerateAuthError(data
, status
));
996 void GaiaAuthFetcher::OnGetTokenResponseFetched(
997 const std::string
& data
,
998 const net::URLRequestStatus
& status
,
1000 std::string access_token
;
1001 int expires_in_secs
= 0;
1002 bool success
= false;
1003 if (status
.is_success() && response_code
== net::HTTP_OK
) {
1004 DVLOG(1) << "GetTokenResponse successful!";
1005 success
= ExtractOAuth2TokenPairResponse(data
, NULL
,
1006 &access_token
, &expires_in_secs
);
1010 consumer_
->OnGetTokenResponseSuccess(
1011 GaiaAuthConsumer::ClientOAuthResult(std::string(), access_token
,
1014 consumer_
->OnGetTokenResponseError(GenerateAuthError(data
, status
));
1018 void GaiaAuthFetcher::OnURLFetchComplete(const net::URLFetcher
* source
) {
1019 fetch_pending_
= false;
1020 // Some of the GAIA requests perform redirects, which results in the final
1021 // URL of the fetcher not being the original URL requested. Therefore use
1022 // the original URL when determining which OnXXX function to call.
1023 const GURL
& url
= source
->GetOriginalURL();
1024 const net::URLRequestStatus
& status
= source
->GetStatus();
1025 int response_code
= source
->GetResponseCode();
1027 source
->GetResponseAsString(&data
);
1029 // Retrieve the response headers from the request. Must only be called after
1030 // the OnURLFetchComplete callback has run.
1032 std::string headers
;
1033 if (source
->GetResponseHeaders())
1034 source
->GetResponseHeaders()->GetNormalizedHeaders(&headers
);
1035 DVLOG(2) << "Response " << url
.spec() << ", code = " << response_code
<< "\n"
1037 DVLOG(2) << "data: " << data
<< "\n";
1040 DispatchFetchedRequest(url
, data
, source
->GetCookies(), status
,
1044 void GaiaAuthFetcher::DispatchFetchedRequest(
1046 const std::string
& data
,
1047 const net::ResponseCookies
& cookies
,
1048 const net::URLRequestStatus
& status
,
1049 int response_code
) {
1050 if (url
== client_login_gurl_
) {
1051 OnClientLoginFetched(data
, status
, response_code
);
1052 } else if (url
== issue_auth_token_gurl_
) {
1053 OnIssueAuthTokenFetched(data
, status
, response_code
);
1054 } else if (base::StartsWithASCII(url
.spec(),
1055 client_login_to_oauth2_gurl_
.spec(), true)) {
1056 OnClientLoginToOAuth2Fetched(data
, cookies
, status
, response_code
);
1057 } else if (url
== oauth2_token_gurl_
) {
1058 OnOAuth2TokenPairFetched(data
, status
, response_code
);
1059 } else if (url
== get_user_info_gurl_
) {
1060 OnGetUserInfoFetched(data
, status
, response_code
);
1061 } else if (url
== merge_session_gurl_
) {
1062 OnMergeSessionFetched(data
, status
, response_code
);
1063 } else if (url
== uberauth_token_gurl_
) {
1064 OnUberAuthTokenFetch(data
, status
, response_code
);
1065 } else if (url
== oauth_login_gurl_
) {
1066 OnOAuthLoginFetched(data
, status
, response_code
);
1067 } else if (url
== oauth2_revoke_gurl_
) {
1068 OnOAuth2RevokeTokenFetched(data
, status
, response_code
);
1069 } else if (url
== list_accounts_gurl_
) {
1070 OnListAccountsFetched(data
, status
, response_code
);
1071 } else if (url
== logout_gurl_
) {
1072 OnLogOutFetched(data
, status
, response_code
);
1073 } else if (url
== get_check_connection_info_url_
) {
1074 OnGetCheckConnectionInfoFetched(data
, status
, response_code
);
1075 } else if (url
== oauth2_iframe_url_
) {
1076 if (requested_service_
== kListIdpServiceRequested
)
1077 OnListIdpSessionsFetched(data
, status
, response_code
);
1078 else if (requested_service_
== kGetTokenResponseRequested
)
1079 OnGetTokenResponseFetched(data
, status
, response_code
);
1088 bool GaiaAuthFetcher::IsSecondFactorSuccess(
1089 const std::string
& alleged_error
) {
1090 return alleged_error
.find(kSecondFactor
) !=
1095 bool GaiaAuthFetcher::IsWebLoginRequiredSuccess(
1096 const std::string
& alleged_error
) {
1097 return alleged_error
.find(kWebLoginRequired
) !=