Subversion Repositories cheapmusic

Rev

Details | Last modification | View Log | RSS feed

Rev Author Line No. Line
25 - 1
<?php
2
/*
3
 * Copyright 2008 Google Inc.
4
 *
5
 * Licensed under the Apache License, Version 2.0 (the "License");
6
 * you may not use this file except in compliance with the License.
7
 * You may obtain a copy of the License at
8
 *
9
 *     http://www.apache.org/licenses/LICENSE-2.0
10
 *
11
 * Unless required by applicable law or agreed to in writing, software
12
 * distributed under the License is distributed on an "AS IS" BASIS,
13
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
 * See the License for the specific language governing permissions and
15
 * limitations under the License.
16
 */
17
 
18
require_once "Google_Verifier.php";
19
require_once "Google_LoginTicket.php";
20
require_once "service/Google_Utils.php";
21
 
22
/**
23
 * Authentication class that deals with the OAuth 2 web-server authentication flow
24
 *
25
 * @author Chris Chabot <chabotc@google.com>
26
 * @author Chirag Shah <chirags@google.com>
27
 *
28
 */
29
class Google_OAuth2 extends Google_Auth {
30
  public $clientId;
31
  public $clientSecret;
32
  public $developerKey;
33
  public $token;
34
  public $redirectUri;
35
  public $state;
36
  public $accessType = 'offline';
37
  public $approvalPrompt = 'force';
38
 
39
  /** @var Google_AssertionCredentials $assertionCredentials */
40
  public $assertionCredentials;
41
 
42
  const OAUTH2_REVOKE_URI = 'https://accounts.google.com/o/oauth2/revoke';
43
  const OAUTH2_TOKEN_URI = 'https://accounts.google.com/o/oauth2/token';
44
  const OAUTH2_AUTH_URL = 'https://accounts.google.com/o/oauth2/auth';
45
  const OAUTH2_FEDERATED_SIGNON_CERTS_URL = 'https://www.googleapis.com/oauth2/v1/certs';
46
  const CLOCK_SKEW_SECS = 300; // five minutes in seconds
47
  const AUTH_TOKEN_LIFETIME_SECS = 300; // five minutes in seconds
48
  const MAX_TOKEN_LIFETIME_SECS = 86400; // one day in seconds
49
 
50
  /**
51
   * Instantiates the class, but does not initiate the login flow, leaving it
52
   * to the discretion of the caller (which is done by calling authenticate()).
53
   */
54
  public function __construct() {
55
    global $apiConfig;
56
 
57
    if (! empty($apiConfig['developer_key'])) {
58
      $this->developerKey = $apiConfig['developer_key'];
59
    }
60
 
61
    if (! empty($apiConfig['oauth2_client_id'])) {
62
      $this->clientId = $apiConfig['oauth2_client_id'];
63
    }
64
 
65
    if (! empty($apiConfig['oauth2_client_secret'])) {
66
      $this->clientSecret = $apiConfig['oauth2_client_secret'];
67
    }
68
 
69
    if (! empty($apiConfig['oauth2_redirect_uri'])) {
70
      $this->redirectUri = $apiConfig['oauth2_redirect_uri'];
71
    }
72
 
73
    if (! empty($apiConfig['oauth2_access_type'])) {
74
      $this->accessType = $apiConfig['oauth2_access_type'];
75
    }
76
 
77
    if (! empty($apiConfig['oauth2_approval_prompt'])) {
78
      $this->approvalPrompt = $apiConfig['oauth2_approval_prompt'];
79
    }
80
  }
81
 
82
  /**
83
   * @param $service
84
   * @param string|null $code
85
   * @throws Google_AuthException
86
   * @return string
87
   */
88
  public function authenticate($service, $code = null) {
89
    if (!$code && isset($_GET['code'])) {
90
      $code = $_GET['code'];
91
    }
92
 
93
    if ($code) {
94
      // We got here from the redirect from a successful authorization grant, fetch the access token
95
      $request = Google_Client::$io->makeRequest(new Google_HttpRequest(self::OAUTH2_TOKEN_URI, 'POST', array(), array(
96
          'code' => $code,
97
          'grant_type' => 'authorization_code',
98
          'redirect_uri' => $this->redirectUri,
99
          'client_id' => $this->clientId,
100
          'client_secret' => $this->clientSecret
101
      )));
102
      if ($request->getResponseHttpCode() == 200) {
103
        $this->setAccessToken($request->getResponseBody());
104
        $this->token['created'] = time();
105
        return $this->getAccessToken();
106
      } else {
107
        $response = $request->getResponseBody();
108
        $decodedResponse = json_decode($response, true);
109
        if ($decodedResponse != null && $decodedResponse['error']) {
110
          $response = $decodedResponse['error'];
111
        }
112
        throw new Google_AuthException("Error fetching OAuth2 access token, message: '$response'", $request->getResponseHttpCode());
113
      }
114
    }
115
 
116
    $authUrl = $this->createAuthUrl($service['scope']);
117
    header('Location: ' . $authUrl);
118
    return true;
119
  }
120
 
121
  /**
122
   * Create a URL to obtain user authorization.
123
   * The authorization endpoint allows the user to first
124
   * authenticate, and then grant/deny the access request.
125
   * @param string $scope The scope is expressed as a list of space-delimited strings.
126
   * @return string
127
   */
128
  public function createAuthUrl($scope) {
129
    $params = array(
130
        'response_type=code',
131
        'redirect_uri=' . urlencode($this->redirectUri),
132
        'client_id=' . urlencode($this->clientId),
133
        'scope=' . urlencode($scope),
134
        'access_type=' . urlencode($this->accessType),
135
        'approval_prompt=' . urlencode($this->approvalPrompt)
136
    );
137
 
138
    if (isset($this->state)) {
139
      $params[] = 'state=' . urlencode($this->state);
140
    }
141
    $params = implode('&', $params);
142
    return self::OAUTH2_AUTH_URL . "?$params";
143
  }
144
 
145
  /**
146
   * @param string $token
147
   * @throws Google_AuthException
148
   */
149
  public function setAccessToken($token) {
150
    $token = json_decode($token, true);
151
    if ($token == null) {
152
      throw new Google_AuthException('Could not json decode the token');
153
    }
154
    if (! isset($token['access_token'])) {
155
      throw new Google_AuthException("Invalid token format");
156
    }
157
    $this->token = $token;
158
  }
159
 
160
  public function getAccessToken() {
161
    return json_encode($this->token);
162
  }
163
 
164
  public function setDeveloperKey($developerKey) {
165
    $this->developerKey = $developerKey;
166
  }
167
 
168
  public function setState($state) {
169
    $this->state = $state;
170
  }
171
 
172
  public function setAccessType($accessType) {
173
    $this->accessType = $accessType;
174
  }
175
 
176
  public function setApprovalPrompt($approvalPrompt) {
177
    $this->approvalPrompt = $approvalPrompt;
178
  }
179
 
180
  public function setAssertionCredentials(Google_AssertionCredentials $creds) {
181
    $this->assertionCredentials = $creds;
182
  }
183
 
184
  /**
185
   * Include an accessToken in a given apiHttpRequest.
186
   * @param Google_HttpRequest $request
187
   * @return Google_HttpRequest
188
   * @throws Google_AuthException
189
   */
190
  public function sign(Google_HttpRequest $request) {
191
    // add the developer key to the request before signing it
192
    if ($this->developerKey) {
193
      $requestUrl = $request->getUrl();
194
      $requestUrl .= (strpos($request->getUrl(), '?') === false) ? '?' : '&';
195
      $requestUrl .=  'key=' . urlencode($this->developerKey);
196
      $request->setUrl($requestUrl);
197
    }
198
 
199
    // Cannot sign the request without an OAuth access token.
200
    if (null == $this->token && null == $this->assertionCredentials) {
201
      return $request;
202
    }
203
 
204
    // Check if the token is set to expire in the next 30 seconds
205
    // (or has already expired).
206
    if ($this->isAccessTokenExpired()) {
207
      if ($this->assertionCredentials) {
208
        $this->refreshTokenWithAssertion();
209
      } else {
210
        if (! array_key_exists('refresh_token', $this->token)) {
211
            throw new Google_AuthException("The OAuth 2.0 access token has expired, "
212
                . "and a refresh token is not available. Refresh tokens are not "
213
                . "returned for responses that were auto-approved.");
214
        }
215
        $this->refreshToken($this->token['refresh_token']);
216
      }
217
    }
218
 
219
    // Add the OAuth2 header to the request
220
    $request->setRequestHeaders(
221
        array('Authorization' => 'Bearer ' . $this->token['access_token'])
222
    );
223
 
224
    return $request;
225
  }
226
 
227
  /**
228
   * Fetches a fresh access token with the given refresh token.
229
   * @param string $refreshToken
230
   * @return void
231
   */
232
  public function refreshToken($refreshToken) {
233
    $this->refreshTokenRequest(array(
234
        'client_id' => $this->clientId,
235
        'client_secret' => $this->clientSecret,
236
        'refresh_token' => $refreshToken,
237
        'grant_type' => 'refresh_token'
238
    ));
239
  }
240
 
241
  /**
242
   * Fetches a fresh access token with a given assertion token.
243
   * @param Google_AssertionCredentials $assertionCredentials optional.
244
   * @return void
245
   */
246
  public function refreshTokenWithAssertion($assertionCredentials = null) {
247
    if (!$assertionCredentials) {
248
      $assertionCredentials = $this->assertionCredentials;
249
    }
250
 
251
    $this->refreshTokenRequest(array(
252
        'grant_type' => 'assertion',
253
        'assertion_type' => $assertionCredentials->assertionType,
254
        'assertion' => $assertionCredentials->generateAssertion(),
255
    ));
256
  }
257
 
258
  private function refreshTokenRequest($params) {
259
    $http = new Google_HttpRequest(self::OAUTH2_TOKEN_URI, 'POST', array(), $params);
260
    $request = Google_Client::$io->makeRequest($http);
261
 
262
    $code = $request->getResponseHttpCode();
263
    $body = $request->getResponseBody();
264
    if (200 == $code) {
265
      $token = json_decode($body, true);
266
      if ($token == null) {
267
        throw new Google_AuthException("Could not json decode the access token");
268
      }
269
 
270
      if (! isset($token['access_token']) || ! isset($token['expires_in'])) {
271
        throw new Google_AuthException("Invalid token format");
272
      }
273
 
274
      $this->token['access_token'] = $token['access_token'];
275
      $this->token['expires_in'] = $token['expires_in'];
276
      $this->token['created'] = time();
277
    } else {
278
      throw new Google_AuthException("Error refreshing the OAuth2 token, message: '$body'", $code);
279
    }
280
  }
281
 
282
    /**
283
     * Revoke an OAuth2 access token or refresh token. This method will revoke the current access
284
     * token, if a token isn't provided.
285
     * @throws Google_AuthException
286
     * @param string|null $token The token (access token or a refresh token) that should be revoked.
287
     * @return boolean Returns True if the revocation was successful, otherwise False.
288
     */
289
  public function revokeToken($token = null) {
290
    if (!$token) {
291
      $token = $this->token['access_token'];
292
    }
293
    $request = new Google_HttpRequest(self::OAUTH2_REVOKE_URI, 'POST', array(), "token=$token");
294
    $response = Google_Client::$io->makeRequest($request);
295
    $code = $response->getResponseHttpCode();
296
    if ($code == 200) {
297
      $this->token = null;
298
      return true;
299
    }
300
 
301
    return false;
302
  }
303
 
304
  /**
305
   * Returns if the access_token is expired.
306
   * @return bool Returns True if the access_token is expired.
307
   */
308
  public function isAccessTokenExpired() {
309
    if (null == $this->token) {
310
      return true;
311
    }
312
 
313
    // If the token is set to expire in the next 30 seconds.
314
    $expired = ($this->token['created']
315
        + ($this->token['expires_in'] - 30)) < time();
316
 
317
    return $expired;
318
  }
319
 
320
  // Gets federated sign-on certificates to use for verifying identity tokens.
321
  // Returns certs as array structure, where keys are key ids, and values
322
  // are PEM encoded certificates.
323
  private function getFederatedSignOnCerts() {
324
    // This relies on makeRequest caching certificate responses.
325
    $request = Google_Client::$io->makeRequest(new Google_HttpRequest(
326
        self::OAUTH2_FEDERATED_SIGNON_CERTS_URL));
327
    if ($request->getResponseHttpCode() == 200) {
328
      $certs = json_decode($request->getResponseBody(), true);
329
      if ($certs) {
330
        return $certs;
331
      }
332
    }
333
    throw new Google_AuthException(
334
        "Failed to retrieve verification certificates: '" .
335
            $request->getResponseBody() . "'.",
336
        $request->getResponseHttpCode());
337
  }
338
 
339
  /**
340
   * Verifies an id token and returns the authenticated apiLoginTicket.
341
   * Throws an exception if the id token is not valid.
342
   * The audience parameter can be used to control which id tokens are
343
   * accepted.  By default, the id token must have been issued to this OAuth2 client.
344
   *
345
   * @param $id_token
346
   * @param $audience
347
   * @return Google_LoginTicket
348
   */
349
  public function verifyIdToken($id_token = null, $audience = null) {
350
    if (!$id_token) {
351
      $id_token = $this->token['id_token'];
352
    }
353
 
354
    $certs = $this->getFederatedSignonCerts();
355
    if (!$audience) {
356
      $audience = $this->clientId;
357
    }
358
    return $this->verifySignedJwtWithCerts($id_token, $certs, $audience);
359
  }
360
 
361
  // Verifies the id token, returns the verified token contents.
362
  // Visible for testing.
363
  function verifySignedJwtWithCerts($jwt, $certs, $required_audience) {
364
    $segments = explode(".", $jwt);
365
    if (count($segments) != 3) {
366
      throw new Google_AuthException("Wrong number of segments in token: $jwt");
367
    }
368
    $signed = $segments[0] . "." . $segments[1];
369
    $signature = Google_Utils::urlSafeB64Decode($segments[2]);
370
 
371
    // Parse envelope.
372
    $envelope = json_decode(Google_Utils::urlSafeB64Decode($segments[0]), true);
373
    if (!$envelope) {
374
      throw new Google_AuthException("Can't parse token envelope: " . $segments[0]);
375
    }
376
 
377
    // Parse token
378
    $json_body = Google_Utils::urlSafeB64Decode($segments[1]);
379
    $payload = json_decode($json_body, true);
380
    if (!$payload) {
381
      throw new Google_AuthException("Can't parse token payload: " . $segments[1]);
382
    }
383
 
384
    // Check signature
385
    $verified = false;
386
    foreach ($certs as $keyName => $pem) {
387
      $public_key = new Google_PemVerifier($pem);
388
      if ($public_key->verify($signed, $signature)) {
389
        $verified = true;
390
        break;
391
      }
392
    }
393
 
394
    if (!$verified) {
395
      throw new Google_AuthException("Invalid token signature: $jwt");
396
    }
397
 
398
    // Check issued-at timestamp
399
    $iat = 0;
400
    if (array_key_exists("iat", $payload)) {
401
      $iat = $payload["iat"];
402
    }
403
    if (!$iat) {
404
      throw new Google_AuthException("No issue time in token: $json_body");
405
    }
406
    $earliest = $iat - self::CLOCK_SKEW_SECS;
407
 
408
    // Check expiration timestamp
409
    $now = time();
410
    $exp = 0;
411
    if (array_key_exists("exp", $payload)) {
412
      $exp = $payload["exp"];
413
    }
414
    if (!$exp) {
415
      throw new Google_AuthException("No expiration time in token: $json_body");
416
    }
417
    if ($exp >= $now + self::MAX_TOKEN_LIFETIME_SECS) {
418
      throw new Google_AuthException(
419
          "Expiration time too far in future: $json_body");
420
    }
421
 
422
    $latest = $exp + self::CLOCK_SKEW_SECS;
423
    if ($now < $earliest) {
424
      throw new Google_AuthException(
425
          "Token used too early, $now < $earliest: $json_body");
426
    }
427
    if ($now > $latest) {
428
      throw new Google_AuthException(
429
          "Token used too late, $now > $latest: $json_body");
430
    }
431
 
432
    // TODO(beaton): check issuer field?
433
 
434
    // Check audience
435
    $aud = $payload["aud"];
436
    if ($aud != $required_audience) {
437
      throw new Google_AuthException("Wrong recipient, $aud != $required_audience: $json_body");
438
    }
439
 
440
    // All good.
441
    return new Google_LoginTicket($envelope, $payload);
442
  }
443
}