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_oauth_client.h"
7 #include "base/json/json_reader.h"
8 #include "base/logging.h"
9 #include "base/memory/scoped_ptr.h"
10 #include "base/strings/string_util.h"
11 #include "base/values.h"
12 #include "google_apis/gaia/gaia_urls.h"
13 #include "net/base/escape.h"
14 #include "net/base/load_flags.h"
15 #include "net/http/http_status_code.h"
16 #include "net/url_request/url_fetcher.h"
17 #include "net/url_request/url_fetcher_delegate.h"
18 #include "net/url_request/url_request_context_getter.h"
22 const char kAccessTokenValue
[] = "access_token";
23 const char kRefreshTokenValue
[] = "refresh_token";
24 const char kExpiresInValue
[] = "expires_in";
29 // Use a non-zero number, so unit tests can differentiate the URLFetcher used by
30 // this class from other fetchers (most other code just hardcodes the ID to 0).
31 const int GaiaOAuthClient::kUrlFetcherId
= 17109006;
33 class GaiaOAuthClient::Core
34 : public base::RefCountedThreadSafe
<GaiaOAuthClient::Core
>,
35 public net::URLFetcherDelegate
{
37 Core(net::URLRequestContextGetter
* request_context_getter
)
39 request_context_getter_(request_context_getter
),
41 request_type_(NO_PENDING_REQUEST
) {
44 void GetTokensFromAuthCode(const OAuthClientInfo
& oauth_client_info
,
45 const std::string
& auth_code
,
47 GaiaOAuthClient::Delegate
* delegate
);
48 void RefreshToken(const OAuthClientInfo
& oauth_client_info
,
49 const std::string
& refresh_token
,
50 const std::vector
<std::string
>& scopes
,
52 GaiaOAuthClient::Delegate
* delegate
);
53 void GetUserEmail(const std::string
& oauth_access_token
,
56 void GetUserId(const std::string
& oauth_access_token
,
59 void GetUserInfo(const std::string
& oauth_access_token
,
62 void GetTokenInfo(const std::string
& qualifier
,
63 const std::string
& query
,
67 // net::URLFetcherDelegate implementation.
68 void OnURLFetchComplete(const net::URLFetcher
* source
) override
;
71 friend class base::RefCountedThreadSafe
<Core
>;
75 TOKENS_FROM_AUTH_CODE
,
85 void GetUserInfoImpl(RequestType type
,
86 const std::string
& oauth_access_token
,
89 void MakeGaiaRequest(const GURL
& url
,
90 const std::string
& post_body
,
92 GaiaOAuthClient::Delegate
* delegate
);
93 void HandleResponse(const net::URLFetcher
* source
,
94 bool* should_retry_request
);
97 scoped_refptr
<net::URLRequestContextGetter
> request_context_getter_
;
98 GaiaOAuthClient::Delegate
* delegate_
;
99 scoped_ptr
<net::URLFetcher
> request_
;
100 RequestType request_type_
;
103 void GaiaOAuthClient::Core::GetTokensFromAuthCode(
104 const OAuthClientInfo
& oauth_client_info
,
105 const std::string
& auth_code
,
107 GaiaOAuthClient::Delegate
* delegate
) {
108 DCHECK_EQ(request_type_
, NO_PENDING_REQUEST
);
109 request_type_
= TOKENS_FROM_AUTH_CODE
;
110 std::string post_body
=
111 "code=" + net::EscapeUrlEncodedData(auth_code
, true) +
112 "&client_id=" + net::EscapeUrlEncodedData(oauth_client_info
.client_id
,
115 net::EscapeUrlEncodedData(oauth_client_info
.client_secret
, true) +
117 net::EscapeUrlEncodedData(oauth_client_info
.redirect_uri
, true) +
118 "&grant_type=authorization_code";
119 MakeGaiaRequest(GURL(GaiaUrls::GetInstance()->oauth2_token_url()),
120 post_body
, max_retries
, delegate
);
123 void GaiaOAuthClient::Core::RefreshToken(
124 const OAuthClientInfo
& oauth_client_info
,
125 const std::string
& refresh_token
,
126 const std::vector
<std::string
>& scopes
,
128 GaiaOAuthClient::Delegate
* delegate
) {
129 DCHECK_EQ(request_type_
, NO_PENDING_REQUEST
);
130 request_type_
= REFRESH_TOKEN
;
131 std::string post_body
=
132 "refresh_token=" + net::EscapeUrlEncodedData(refresh_token
, true) +
133 "&client_id=" + net::EscapeUrlEncodedData(oauth_client_info
.client_id
,
136 net::EscapeUrlEncodedData(oauth_client_info
.client_secret
, true) +
137 "&grant_type=refresh_token";
139 if (!scopes
.empty()) {
140 std::string scopes_string
= base::JoinString(scopes
, " ");
141 post_body
+= "&scope=" + net::EscapeUrlEncodedData(scopes_string
, true);
144 MakeGaiaRequest(GURL(GaiaUrls::GetInstance()->oauth2_token_url()),
145 post_body
, max_retries
, delegate
);
148 void GaiaOAuthClient::Core::GetUserEmail(const std::string
& oauth_access_token
,
150 Delegate
* delegate
) {
151 GetUserInfoImpl(USER_EMAIL
, oauth_access_token
, max_retries
, delegate
);
154 void GaiaOAuthClient::Core::GetUserId(const std::string
& oauth_access_token
,
156 Delegate
* delegate
) {
157 GetUserInfoImpl(USER_ID
, oauth_access_token
, max_retries
, delegate
);
160 void GaiaOAuthClient::Core::GetUserInfo(const std::string
& oauth_access_token
,
162 Delegate
* delegate
) {
163 GetUserInfoImpl(USER_INFO
, oauth_access_token
, max_retries
, delegate
);
166 void GaiaOAuthClient::Core::GetUserInfoImpl(
168 const std::string
& oauth_access_token
,
170 Delegate
* delegate
) {
171 DCHECK_EQ(request_type_
, NO_PENDING_REQUEST
);
172 DCHECK(!request_
.get());
173 request_type_
= type
;
174 delegate_
= delegate
;
176 request_
= net::URLFetcher::Create(
177 kUrlFetcherId
, GURL(GaiaUrls::GetInstance()->oauth_user_info_url()),
178 net::URLFetcher::GET
, this);
179 request_
->SetRequestContext(request_context_getter_
.get());
180 request_
->AddExtraRequestHeader("Authorization: OAuth " + oauth_access_token
);
181 request_
->SetMaxRetriesOn5xx(max_retries
);
182 request_
->SetLoadFlags(net::LOAD_DO_NOT_SEND_COOKIES
|
183 net::LOAD_DO_NOT_SAVE_COOKIES
);
185 // Fetchers are sometimes cancelled because a network change was detected,
186 // especially at startup and after sign-in on ChromeOS. Retrying once should
187 // be enough in those cases; let the fetcher retry up to 3 times just in case.
188 // http://crbug.com/163710
189 request_
->SetAutomaticallyRetryOnNetworkChanges(3);
193 void GaiaOAuthClient::Core::GetTokenInfo(const std::string
& qualifier
,
194 const std::string
& query
,
196 Delegate
* delegate
) {
197 DCHECK_EQ(request_type_
, NO_PENDING_REQUEST
);
198 DCHECK(!request_
.get());
199 request_type_
= TOKEN_INFO
;
200 std::string post_body
=
201 qualifier
+ "=" + net::EscapeUrlEncodedData(query
, true);
202 MakeGaiaRequest(GURL(GaiaUrls::GetInstance()->oauth2_token_info_url()),
208 void GaiaOAuthClient::Core::MakeGaiaRequest(
210 const std::string
& post_body
,
212 GaiaOAuthClient::Delegate
* delegate
) {
213 DCHECK(!request_
.get()) << "Tried to fetch two things at once!";
214 delegate_
= delegate
;
217 net::URLFetcher::Create(kUrlFetcherId
, url
, net::URLFetcher::POST
, this);
218 request_
->SetRequestContext(request_context_getter_
.get());
219 request_
->SetUploadData("application/x-www-form-urlencoded", post_body
);
220 request_
->SetMaxRetriesOn5xx(max_retries
);
221 request_
->SetLoadFlags(net::LOAD_DO_NOT_SEND_COOKIES
|
222 net::LOAD_DO_NOT_SAVE_COOKIES
);
223 // See comment on SetAutomaticallyRetryOnNetworkChanges() above.
224 request_
->SetAutomaticallyRetryOnNetworkChanges(3);
228 // URLFetcher::Delegate implementation.
229 void GaiaOAuthClient::Core::OnURLFetchComplete(
230 const net::URLFetcher
* source
) {
231 bool should_retry
= false;
232 HandleResponse(source
, &should_retry
);
234 // Explicitly call ReceivedContentWasMalformed() to ensure the current
235 // request gets counted as a failure for calculation of the back-off
236 // period. If it was already a failure by status code, this call will
238 request_
->ReceivedContentWasMalformed();
240 // We must set our request_context_getter_ again because
241 // URLFetcher::Core::RetryOrCompleteUrlFetch resets it to NULL...
242 request_
->SetRequestContext(request_context_getter_
.get());
247 void GaiaOAuthClient::Core::HandleResponse(
248 const net::URLFetcher
* source
,
249 bool* should_retry_request
) {
250 // Move ownership of the request fetcher into a local scoped_ptr which
251 // will be nuked when we're done handling the request, unless we need
252 // to retry, in which case ownership will be returned to request_.
253 scoped_ptr
<net::URLFetcher
> old_request
= request_
.Pass();
254 DCHECK_EQ(source
, old_request
.get());
256 // HTTP_BAD_REQUEST means the arguments are invalid. HTTP_UNAUTHORIZED means
257 // the access or refresh token is invalid. No point retrying. We are
259 int response_code
= source
->GetResponseCode();
260 if (response_code
== net::HTTP_BAD_REQUEST
||
261 response_code
== net::HTTP_UNAUTHORIZED
) {
262 delegate_
->OnOAuthError();
266 scoped_ptr
<base::DictionaryValue
> response_dict
;
267 if (source
->GetResponseCode() == net::HTTP_OK
) {
269 source
->GetResponseAsString(&data
);
270 scoped_ptr
<base::Value
> message_value
= base::JSONReader::Read(data
);
271 if (message_value
.get() &&
272 message_value
->IsType(base::Value::TYPE_DICTIONARY
)) {
274 static_cast<base::DictionaryValue
*>(message_value
.release()));
278 if (!response_dict
.get()) {
279 // If we don't have an access token yet and the the error was not
280 // RC_BAD_REQUEST, we may need to retry.
281 if ((source
->GetMaxRetriesOn5xx() != -1) &&
282 (num_retries_
>= source
->GetMaxRetriesOn5xx())) {
283 // Retry limit reached. Give up.
284 delegate_
->OnNetworkError(source
->GetResponseCode());
286 request_
= old_request
.Pass();
287 *should_retry_request
= true;
292 RequestType type
= request_type_
;
293 request_type_
= NO_PENDING_REQUEST
;
298 response_dict
->GetString("email", &email
);
299 delegate_
->OnGetUserEmailResponse(email
);
305 response_dict
->GetString("id", &id
);
306 delegate_
->OnGetUserIdResponse(id
);
311 delegate_
->OnGetUserInfoResponse(response_dict
.Pass());
316 delegate_
->OnGetTokenInfoResponse(response_dict
.Pass());
320 case TOKENS_FROM_AUTH_CODE
:
321 case REFRESH_TOKEN
: {
322 std::string access_token
;
323 std::string refresh_token
;
324 int expires_in_seconds
= 0;
325 response_dict
->GetString(kAccessTokenValue
, &access_token
);
326 response_dict
->GetString(kRefreshTokenValue
, &refresh_token
);
327 response_dict
->GetInteger(kExpiresInValue
, &expires_in_seconds
);
329 if (access_token
.empty()) {
330 delegate_
->OnOAuthError();
334 if (type
== REFRESH_TOKEN
) {
335 delegate_
->OnRefreshTokenResponse(access_token
, expires_in_seconds
);
337 delegate_
->OnGetTokensResponse(refresh_token
,
349 GaiaOAuthClient::GaiaOAuthClient(net::URLRequestContextGetter
* context_getter
) {
350 core_
= new Core(context_getter
);
353 GaiaOAuthClient::~GaiaOAuthClient() {
356 void GaiaOAuthClient::GetTokensFromAuthCode(
357 const OAuthClientInfo
& oauth_client_info
,
358 const std::string
& auth_code
,
360 Delegate
* delegate
) {
361 return core_
->GetTokensFromAuthCode(oauth_client_info
,
367 void GaiaOAuthClient::RefreshToken(
368 const OAuthClientInfo
& oauth_client_info
,
369 const std::string
& refresh_token
,
370 const std::vector
<std::string
>& scopes
,
372 Delegate
* delegate
) {
373 return core_
->RefreshToken(oauth_client_info
,
380 void GaiaOAuthClient::GetUserEmail(const std::string
& access_token
,
382 Delegate
* delegate
) {
383 return core_
->GetUserEmail(access_token
, max_retries
, delegate
);
386 void GaiaOAuthClient::GetUserId(const std::string
& access_token
,
388 Delegate
* delegate
) {
389 return core_
->GetUserId(access_token
, max_retries
, delegate
);
392 void GaiaOAuthClient::GetUserInfo(const std::string
& access_token
,
394 Delegate
* delegate
) {
395 return core_
->GetUserInfo(access_token
, max_retries
, delegate
);
398 void GaiaOAuthClient::GetTokenInfo(const std::string
& access_token
,
400 Delegate
* delegate
) {
401 return core_
->GetTokenInfo("access_token", access_token
, max_retries
,
405 void GaiaOAuthClient::GetTokenHandleInfo(const std::string
& token_handle
,
407 Delegate
* delegate
) {
408 return core_
->GetTokenInfo("token_handle", token_handle
, max_retries
,