Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(1586)

Side by Side Diff: google_apis/gaia/oauth2_access_token_fetcher_impl.cc

Issue 182573003: Extract OAuth2AccessTokenFetcher interface. (Closed) Base URL: svn://svn.chromium.org/chrome/trunk/src
Patch Set: Fix compile errors in chrome Created 6 years, 9 months ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View unified diff | Download patch | Annotate | Revision Log
OLDNEW
1 // Copyright (c) 2012 The Chromium Authors. All rights reserved. 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 2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file. 3 // found in the LICENSE file.
4 4
5 #include "google_apis/gaia/oauth2_access_token_fetcher.h" 5 #include "google_apis/gaia/oauth2_access_token_fetcher_impl.h"
6 6
7 #include <algorithm> 7 #include <algorithm>
8 #include <string> 8 #include <string>
9 #include <vector> 9 #include <vector>
10 10
11 #include "base/json/json_reader.h" 11 #include "base/json/json_reader.h"
12 #include "base/metrics/histogram.h" 12 #include "base/metrics/histogram.h"
13 #include "base/metrics/sparse_histogram.h" 13 #include "base/metrics/sparse_histogram.h"
14 #include "base/strings/string_util.h" 14 #include "base/strings/string_util.h"
15 #include "base/strings/stringprintf.h" 15 #include "base/strings/stringprintf.h"
(...skipping 28 matching lines...) Expand all
44 "refresh_token=%s&" 44 "refresh_token=%s&"
45 "scope=%s"; 45 "scope=%s";
46 46
47 static const char kAccessTokenKey[] = "access_token"; 47 static const char kAccessTokenKey[] = "access_token";
48 static const char kExpiresInKey[] = "expires_in"; 48 static const char kExpiresInKey[] = "expires_in";
49 static const char kErrorKey[] = "error"; 49 static const char kErrorKey[] = "error";
50 50
51 // Enumerated constants for logging server responses on 400 errors, matching 51 // Enumerated constants for logging server responses on 400 errors, matching
52 // RFC 6749. 52 // RFC 6749.
53 enum OAuth2ErrorCodesForHistogram { 53 enum OAuth2ErrorCodesForHistogram {
54 OAUTH2_ACCESS_ERROR_INVALID_REQUEST = 0, 54 OAUTH2_ACCESS_ERROR_INVALID_REQUEST = 0,
55 OAUTH2_ACCESS_ERROR_INVALID_CLIENT, 55 OAUTH2_ACCESS_ERROR_INVALID_CLIENT,
56 OAUTH2_ACCESS_ERROR_INVALID_GRANT, 56 OAUTH2_ACCESS_ERROR_INVALID_GRANT,
57 OAUTH2_ACCESS_ERROR_UNAUTHORIZED_CLIENT, 57 OAUTH2_ACCESS_ERROR_UNAUTHORIZED_CLIENT,
58 OAUTH2_ACCESS_ERROR_UNSUPPORTED_GRANT_TYPE, 58 OAUTH2_ACCESS_ERROR_UNSUPPORTED_GRANT_TYPE,
59 OAUTH2_ACCESS_ERROR_INVALID_SCOPE, 59 OAUTH2_ACCESS_ERROR_INVALID_SCOPE,
60 OAUTH2_ACCESS_ERROR_UNKNOWN, 60 OAUTH2_ACCESS_ERROR_UNKNOWN,
61 OAUTH2_ACCESS_ERROR_COUNT 61 OAUTH2_ACCESS_ERROR_COUNT
62 }; 62 };
63 63
64 OAuth2ErrorCodesForHistogram OAuth2ErrorToHistogramValue( 64 OAuth2ErrorCodesForHistogram OAuth2ErrorToHistogramValue(
65 const std::string& error) { 65 const std::string& error) {
66 if (error == "invalid_request") 66 if (error == "invalid_request")
67 return OAUTH2_ACCESS_ERROR_INVALID_REQUEST; 67 return OAUTH2_ACCESS_ERROR_INVALID_REQUEST;
68 else if (error == "invalid_client") 68 else if (error == "invalid_client")
69 return OAUTH2_ACCESS_ERROR_INVALID_CLIENT; 69 return OAUTH2_ACCESS_ERROR_INVALID_CLIENT;
70 else if (error == "invalid_grant") 70 else if (error == "invalid_grant")
71 return OAUTH2_ACCESS_ERROR_INVALID_GRANT; 71 return OAUTH2_ACCESS_ERROR_INVALID_GRANT;
(...skipping 17 matching lines...) Expand all
89 return GoogleServiceAuthError::FromConnectionError(status.error()); 89 return GoogleServiceAuthError::FromConnectionError(status.error());
90 } 90 }
91 } 91 }
92 92
93 static URLFetcher* CreateFetcher(URLRequestContextGetter* getter, 93 static URLFetcher* CreateFetcher(URLRequestContextGetter* getter,
94 const GURL& url, 94 const GURL& url,
95 const std::string& body, 95 const std::string& body,
96 URLFetcherDelegate* delegate) { 96 URLFetcherDelegate* delegate) {
97 bool empty_body = body.empty(); 97 bool empty_body = body.empty();
98 URLFetcher* result = net::URLFetcher::Create( 98 URLFetcher* result = net::URLFetcher::Create(
99 0, url, 99 0, url, empty_body ? URLFetcher::GET : URLFetcher::POST, delegate);
100 empty_body ? URLFetcher::GET : URLFetcher::POST,
101 delegate);
102 100
103 result->SetRequestContext(getter); 101 result->SetRequestContext(getter);
104 result->SetLoadFlags(net::LOAD_DO_NOT_SEND_COOKIES | 102 result->SetLoadFlags(net::LOAD_DO_NOT_SEND_COOKIES |
105 net::LOAD_DO_NOT_SAVE_COOKIES); 103 net::LOAD_DO_NOT_SAVE_COOKIES);
106 // Fetchers are sometimes cancelled because a network change was detected, 104 // Fetchers are sometimes cancelled because a network change was detected,
107 // especially at startup and after sign-in on ChromeOS. Retrying once should 105 // especially at startup and after sign-in on ChromeOS. Retrying once should
108 // be enough in those cases; let the fetcher retry up to 3 times just in case. 106 // be enough in those cases; let the fetcher retry up to 3 times just in case.
109 // http://crbug.com/163710 107 // http://crbug.com/163710
110 result->SetAutomaticallyRetryOnNetworkChanges(3); 108 result->SetAutomaticallyRetryOnNetworkChanges(3);
111 109
112 if (!empty_body) 110 if (!empty_body)
113 result->SetUploadData("application/x-www-form-urlencoded", body); 111 result->SetUploadData("application/x-www-form-urlencoded", body);
114 112
115 return result; 113 return result;
116 } 114 }
117 } // namespace 115 } // namespace
118 116
119 OAuth2AccessTokenFetcher::OAuth2AccessTokenFetcher( 117 OAuth2AccessTokenFetcherImpl::OAuth2AccessTokenFetcherImpl(
120 OAuth2AccessTokenConsumer* consumer,
121 URLRequestContextGetter* getter) 118 URLRequestContextGetter* getter)
122 : consumer_(consumer), 119 : consumer_(NULL), getter_(getter), state_(INITIAL) {}
123 getter_(getter),
124 state_(INITIAL) { }
125 120
126 OAuth2AccessTokenFetcher::~OAuth2AccessTokenFetcher() { } 121 OAuth2AccessTokenFetcherImpl::~OAuth2AccessTokenFetcherImpl() {}
127 122
128 void OAuth2AccessTokenFetcher::CancelRequest() { 123 void OAuth2AccessTokenFetcherImpl::CancelRequest() { fetcher_.reset(); }
129 fetcher_.reset();
130 }
131 124
132 void OAuth2AccessTokenFetcher::Start(const std::string& client_id, 125 void OAuth2AccessTokenFetcherImpl::Start(const std::string& client_id,
133 const std::string& client_secret, 126 const std::string& client_secret,
134 const std::string& refresh_token, 127 const std::string& refresh_token,
135 const std::vector<std::string>& scopes) { 128 const std::vector<std::string>& scopes,
129 OAuth2AccessTokenConsumer* consumer) {
130 DCHECK(!consumer_);
136 client_id_ = client_id; 131 client_id_ = client_id;
137 client_secret_ = client_secret; 132 client_secret_ = client_secret;
138 refresh_token_ = refresh_token; 133 refresh_token_ = refresh_token;
139 scopes_ = scopes; 134 scopes_ = scopes;
135 consumer_ = consumer;
140 StartGetAccessToken(); 136 StartGetAccessToken();
141 } 137 }
142 138
143 void OAuth2AccessTokenFetcher::StartGetAccessToken() { 139 void OAuth2AccessTokenFetcherImpl::StartGetAccessToken() {
144 CHECK_EQ(INITIAL, state_); 140 CHECK_EQ(INITIAL, state_);
145 state_ = GET_ACCESS_TOKEN_STARTED; 141 state_ = GET_ACCESS_TOKEN_STARTED;
146 fetcher_.reset(CreateFetcher( 142 fetcher_.reset(
147 getter_, 143 CreateFetcher(getter_,
148 MakeGetAccessTokenUrl(), 144 MakeGetAccessTokenUrl(),
149 MakeGetAccessTokenBody( 145 MakeGetAccessTokenBody(
150 client_id_, client_secret_, refresh_token_, scopes_), 146 client_id_, client_secret_, refresh_token_, scopes_),
151 this)); 147 this));
152 fetcher_->Start(); // OnURLFetchComplete will be called. 148 fetcher_->Start(); // OnURLFetchComplete will be called.
153 } 149 }
154 150
155 void OAuth2AccessTokenFetcher::EndGetAccessToken( 151 void OAuth2AccessTokenFetcherImpl::EndGetAccessToken(
156 const net::URLFetcher* source) { 152 const net::URLFetcher* source) {
157 CHECK_EQ(GET_ACCESS_TOKEN_STARTED, state_); 153 CHECK_EQ(GET_ACCESS_TOKEN_STARTED, state_);
158 state_ = GET_ACCESS_TOKEN_DONE; 154 state_ = GET_ACCESS_TOKEN_DONE;
159 155
160 URLRequestStatus status = source->GetStatus(); 156 URLRequestStatus status = source->GetStatus();
161 int histogram_value = status.is_success() ? source->GetResponseCode() : 157 int histogram_value =
162 status.error(); 158 status.is_success() ? source->GetResponseCode() : status.error();
163 UMA_HISTOGRAM_SPARSE_SLOWLY("Gaia.ResponseCodesForOAuth2AccessToken", 159 UMA_HISTOGRAM_SPARSE_SLOWLY("Gaia.ResponseCodesForOAuth2AccessToken",
164 histogram_value); 160 histogram_value);
165 if (!status.is_success()) { 161 if (!status.is_success()) {
166 OnGetTokenFailure(CreateAuthError(status)); 162 OnGetTokenFailure(CreateAuthError(status));
167 return; 163 return;
168 } 164 }
169 165
170 switch (source->GetResponseCode()) { 166 switch (source->GetResponseCode()) {
171 case net::HTTP_OK: 167 case net::HTTP_OK:
172 break; 168 break;
173 case net::HTTP_FORBIDDEN: 169 case net::HTTP_FORBIDDEN:
174 case net::HTTP_INTERNAL_SERVER_ERROR: 170 case net::HTTP_INTERNAL_SERVER_ERROR:
175 // HTTP_FORBIDDEN (403) is treated as temporary error, because it may be 171 // HTTP_FORBIDDEN (403) is treated as temporary error, because it may be
176 // '403 Rate Limit Exeeded.' 500 is always treated as transient. 172 // '403 Rate Limit Exeeded.' 500 is always treated as transient.
177 OnGetTokenFailure(GoogleServiceAuthError( 173 OnGetTokenFailure(
178 GoogleServiceAuthError::SERVICE_UNAVAILABLE)); 174 GoogleServiceAuthError(GoogleServiceAuthError::SERVICE_UNAVAILABLE));
179 return; 175 return;
180 case net::HTTP_BAD_REQUEST: { 176 case net::HTTP_BAD_REQUEST: {
181 // HTTP_BAD_REQUEST (400) usually contains error as per 177 // HTTP_BAD_REQUEST (400) usually contains error as per
182 // http://tools.ietf.org/html/rfc6749#section-5.2. 178 // http://tools.ietf.org/html/rfc6749#section-5.2.
183 std::string gaia_error; 179 std::string gaia_error;
184 if (!ParseGetAccessTokenFailureResponse(source, &gaia_error)) { 180 if (!ParseGetAccessTokenFailureResponse(source, &gaia_error)) {
185 OnGetTokenFailure(GoogleServiceAuthError( 181 OnGetTokenFailure(
186 GoogleServiceAuthError::SERVICE_ERROR)); 182 GoogleServiceAuthError(GoogleServiceAuthError::SERVICE_ERROR));
187 return; 183 return;
188 } 184 }
189 185
190 OAuth2ErrorCodesForHistogram access_error(OAuth2ErrorToHistogramValue( 186 OAuth2ErrorCodesForHistogram access_error(
191 gaia_error)); 187 OAuth2ErrorToHistogramValue(gaia_error));
192 UMA_HISTOGRAM_ENUMERATION("Gaia.BadRequestTypeForOAuth2AccessToken", 188 UMA_HISTOGRAM_ENUMERATION("Gaia.BadRequestTypeForOAuth2AccessToken",
193 access_error, OAUTH2_ACCESS_ERROR_COUNT); 189 access_error,
190 OAUTH2_ACCESS_ERROR_COUNT);
194 191
195 OnGetTokenFailure(access_error == OAUTH2_ACCESS_ERROR_INVALID_GRANT ? 192 OnGetTokenFailure(
196 GoogleServiceAuthError( 193 access_error == OAUTH2_ACCESS_ERROR_INVALID_GRANT
197 GoogleServiceAuthError::INVALID_GAIA_CREDENTIALS) : 194 ? GoogleServiceAuthError(
198 GoogleServiceAuthError( 195 GoogleServiceAuthError::INVALID_GAIA_CREDENTIALS)
199 GoogleServiceAuthError::SERVICE_ERROR)); 196 : GoogleServiceAuthError(GoogleServiceAuthError::SERVICE_ERROR));
200 return; 197 return;
201 } 198 }
202 default: 199 default:
203 // The other errors are treated as permanent error. 200 // The other errors are treated as permanent error.
204 OnGetTokenFailure(GoogleServiceAuthError( 201 OnGetTokenFailure(GoogleServiceAuthError(
205 GoogleServiceAuthError::INVALID_GAIA_CREDENTIALS)); 202 GoogleServiceAuthError::INVALID_GAIA_CREDENTIALS));
206 return; 203 return;
207 } 204 }
208 205
209 // The request was successfully fetched and it returned OK. 206 // The request was successfully fetched and it returned OK.
210 // Parse out the access token and the expiration time. 207 // Parse out the access token and the expiration time.
211 std::string access_token; 208 std::string access_token;
212 int expires_in; 209 int expires_in;
213 if (!ParseGetAccessTokenSuccessResponse( 210 if (!ParseGetAccessTokenSuccessResponse(source, &access_token, &expires_in)) {
214 source, &access_token, &expires_in)) {
215 DLOG(WARNING) << "Response doesn't match expected format"; 211 DLOG(WARNING) << "Response doesn't match expected format";
216 OnGetTokenFailure( 212 OnGetTokenFailure(
217 GoogleServiceAuthError(GoogleServiceAuthError::SERVICE_UNAVAILABLE)); 213 GoogleServiceAuthError(GoogleServiceAuthError::SERVICE_UNAVAILABLE));
218 return; 214 return;
219 } 215 }
220 // The token will expire in |expires_in| seconds. Take a 10% error margin to 216 // The token will expire in |expires_in| seconds. Take a 10% error margin to
221 // prevent reusing a token too close to its expiration date. 217 // prevent reusing a token too close to its expiration date.
222 OnGetTokenSuccess( 218 OnGetTokenSuccess(
223 access_token, 219 access_token,
224 base::Time::Now() + base::TimeDelta::FromSeconds(9 * expires_in / 10)); 220 base::Time::Now() + base::TimeDelta::FromSeconds(9 * expires_in / 10));
225 } 221 }
226 222
227 void OAuth2AccessTokenFetcher::OnGetTokenSuccess( 223 void OAuth2AccessTokenFetcherImpl::OnGetTokenSuccess(
228 const std::string& access_token, 224 const std::string& access_token,
229 const base::Time& expiration_time) { 225 const base::Time& expiration_time) {
230 consumer_->OnGetTokenSuccess(access_token, expiration_time); 226 consumer_->OnGetTokenSuccess(access_token, expiration_time);
231 } 227 }
232 228
233 void OAuth2AccessTokenFetcher::OnGetTokenFailure( 229 void OAuth2AccessTokenFetcherImpl::OnGetTokenFailure(
234 const GoogleServiceAuthError& error) { 230 const GoogleServiceAuthError& error) {
235 state_ = ERROR_STATE; 231 state_ = ERROR_STATE;
236 consumer_->OnGetTokenFailure(error); 232 consumer_->OnGetTokenFailure(error);
237 } 233 }
238 234
239 void OAuth2AccessTokenFetcher::OnURLFetchComplete( 235 void OAuth2AccessTokenFetcherImpl::OnURLFetchComplete(
240 const net::URLFetcher* source) { 236 const net::URLFetcher* source) {
241 CHECK(source); 237 CHECK(source);
242 CHECK(state_ == GET_ACCESS_TOKEN_STARTED); 238 CHECK(state_ == GET_ACCESS_TOKEN_STARTED);
243 EndGetAccessToken(source); 239 EndGetAccessToken(source);
244 } 240 }
245 241
246 // static 242 // static
247 GURL OAuth2AccessTokenFetcher::MakeGetAccessTokenUrl() { 243 GURL OAuth2AccessTokenFetcherImpl::MakeGetAccessTokenUrl() {
248 return GaiaUrls::GetInstance()->oauth2_token_url(); 244 return GaiaUrls::GetInstance()->oauth2_token_url();
249 } 245 }
250 246
251 // static 247 // static
252 std::string OAuth2AccessTokenFetcher::MakeGetAccessTokenBody( 248 std::string OAuth2AccessTokenFetcherImpl::MakeGetAccessTokenBody(
253 const std::string& client_id, 249 const std::string& client_id,
254 const std::string& client_secret, 250 const std::string& client_secret,
255 const std::string& refresh_token, 251 const std::string& refresh_token,
256 const std::vector<std::string>& scopes) { 252 const std::vector<std::string>& scopes) {
257 std::string enc_client_id = net::EscapeUrlEncodedData(client_id, true); 253 std::string enc_client_id = net::EscapeUrlEncodedData(client_id, true);
258 std::string enc_client_secret = 254 std::string enc_client_secret =
259 net::EscapeUrlEncodedData(client_secret, true); 255 net::EscapeUrlEncodedData(client_secret, true);
260 std::string enc_refresh_token = 256 std::string enc_refresh_token =
261 net::EscapeUrlEncodedData(refresh_token, true); 257 net::EscapeUrlEncodedData(refresh_token, true);
262 if (scopes.empty()) { 258 if (scopes.empty()) {
263 return base::StringPrintf( 259 return base::StringPrintf(kGetAccessTokenBodyFormat,
264 kGetAccessTokenBodyFormat, 260 enc_client_id.c_str(),
265 enc_client_id.c_str(), 261 enc_client_secret.c_str(),
266 enc_client_secret.c_str(), 262 enc_refresh_token.c_str());
267 enc_refresh_token.c_str());
268 } else { 263 } else {
269 std::string scopes_string = JoinString(scopes, ' '); 264 std::string scopes_string = JoinString(scopes, ' ');
270 return base::StringPrintf( 265 return base::StringPrintf(
271 kGetAccessTokenBodyWithScopeFormat, 266 kGetAccessTokenBodyWithScopeFormat,
272 enc_client_id.c_str(), 267 enc_client_id.c_str(),
273 enc_client_secret.c_str(), 268 enc_client_secret.c_str(),
274 enc_refresh_token.c_str(), 269 enc_refresh_token.c_str(),
275 net::EscapeUrlEncodedData(scopes_string, true).c_str()); 270 net::EscapeUrlEncodedData(scopes_string, true).c_str());
276 } 271 }
277 } 272 }
278 273
279 scoped_ptr<base::DictionaryValue> ParseGetAccessTokenResponse( 274 scoped_ptr<base::DictionaryValue> ParseGetAccessTokenResponse(
Joao da Silva 2014/03/03 20:58:19 Seems like this should be static or in the anonymo
msarda 2014/03/04 12:37:13 I added a TODO.
Roger Tawa OOO till Jul 10th 2014/03/04 15:20:02 Should just do it here. Put the function in an an
msarda 2014/03/04 16:13:54 Done.
280 const net::URLFetcher* source) { 275 const net::URLFetcher* source) {
281 CHECK(source); 276 CHECK(source);
282 277
283 std::string data; 278 std::string data;
284 source->GetResponseAsString(&data); 279 source->GetResponseAsString(&data);
285 scoped_ptr<base::Value> value(base::JSONReader::Read(data)); 280 scoped_ptr<base::Value> value(base::JSONReader::Read(data));
286 if (!value.get() || value->GetType() != base::Value::TYPE_DICTIONARY) 281 if (!value.get() || value->GetType() != base::Value::TYPE_DICTIONARY)
287 value.reset(); 282 value.reset();
288 283
289 return scoped_ptr<base::DictionaryValue>( 284 return scoped_ptr<base::DictionaryValue>(
290 static_cast<base::DictionaryValue*>(value.release())); 285 static_cast<base::DictionaryValue*>(value.release()));
291 } 286 }
292 287
293 // static 288 // static
294 bool OAuth2AccessTokenFetcher::ParseGetAccessTokenSuccessResponse( 289 bool OAuth2AccessTokenFetcherImpl::ParseGetAccessTokenSuccessResponse(
295 const net::URLFetcher* source, 290 const net::URLFetcher* source,
296 std::string* access_token, 291 std::string* access_token,
297 int* expires_in) { 292 int* expires_in) {
298 CHECK(access_token); 293 CHECK(access_token);
299 scoped_ptr<base::DictionaryValue> value = ParseGetAccessTokenResponse( 294 scoped_ptr<base::DictionaryValue> value = ParseGetAccessTokenResponse(source);
300 source);
301 if (value.get() == NULL) 295 if (value.get() == NULL)
302 return false; 296 return false;
303 297
304 return value->GetString(kAccessTokenKey, access_token) && 298 return value->GetString(kAccessTokenKey, access_token) &&
305 value->GetInteger(kExpiresInKey, expires_in); 299 value->GetInteger(kExpiresInKey, expires_in);
306 } 300 }
307 301
308 // static 302 // static
309 bool OAuth2AccessTokenFetcher::ParseGetAccessTokenFailureResponse( 303 bool OAuth2AccessTokenFetcherImpl::ParseGetAccessTokenFailureResponse(
310 const net::URLFetcher* source, 304 const net::URLFetcher* source,
311 std::string* error) { 305 std::string* error) {
312 CHECK(error); 306 CHECK(error);
313 scoped_ptr<base::DictionaryValue> value = ParseGetAccessTokenResponse( 307 scoped_ptr<base::DictionaryValue> value = ParseGetAccessTokenResponse(source);
314 source);
315 if (value.get() == NULL) 308 if (value.get() == NULL)
316 return false; 309 return false;
317 return value->GetString(kErrorKey, error); 310 return value->GetString(kErrorKey, error);
318 } 311 }
OLDNEW

Powered by Google App Engine
This is Rietveld 408576698