added google xoauth2 support + fixed a journaling issue

This commit is contained in:
SJ
2012-09-28 10:34:04 +02:00
parent f930aacc84
commit 55de53bb26
111 changed files with 38812 additions and 4 deletions

View File

@ -0,0 +1,37 @@
<?php
/*
* Copyright 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
require_once "apiAuthNone.php";
require_once "apiOAuth.php";
require_once "apiOAuth2.php";
/**
* Abstract class for the Authentication in the API client
* @author Chris Chabot <chabotc@google.com>
*
*/
abstract class apiAuth {
abstract public function authenticate($service);
abstract public function sign(apiHttpRequest $request);
abstract public function createAuthUrl($scope);
abstract public function getAccessToken();
abstract public function setAccessToken($accessToken);
abstract public function setDeveloperKey($developerKey);
abstract public function refreshToken($refreshToken);
abstract public function revokeToken();
}

View File

@ -0,0 +1,48 @@
<?php
/*
* Copyright 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* Do-nothing authentication implementation, use this if you want to make un-authenticated calls
* @author Chris Chabot <chabotc@google.com>
* @author Chirag Shah <chirags@google.com>
*/
class apiAuthNone extends apiAuth {
public $key = null;
public function __construct() {
global $apiConfig;
if (!empty($apiConfig['developer_key'])) {
$this->setDeveloperKey($apiConfig['developer_key']);
}
}
public function setDeveloperKey($key) {$this->key = $key;}
public function authenticate($service) {/*noop*/}
public function setAccessToken($accessToken) {/* noop*/}
public function getAccessToken() {return null;}
public function createAuthUrl($scope) {return null;}
public function refreshToken($refreshToken) {/* noop*/}
public function revokeToken() {/* noop*/}
public function sign(apiHttpRequest $request) {
if ($this->key) {
$request->setUrl($request->getUrl() . ((strpos($request->getUrl(), '?') === false) ? '?' : '&')
. 'key='.urlencode($this->key));
}
return $request;
}
}

View File

@ -0,0 +1,60 @@
<?php
/*
* Copyright 2011 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* Class to hold information about an authenticated login.
*
* @author Brian Eaton <beaton@google.com>
*/
class apiLoginTicket {
const USER_ATTR = "id";
// Information from id token envelope.
private $envelope;
// Information from id token payload.
private $payload;
/**
* Creates a user based on the supplied token.
*
* envelope: header from a verified authentication token.
* payload: information from a verified authentication token.
*/
public function __construct($envelope, $payload) {
$this->envelope = $envelope;
$this->payload = $payload;
}
/**
* Returns the numeric identifier for the user.
*/
public function getUserId() {
if (array_key_exists(self::USER_ATTR, $this->payload)) {
return $this->payload[self::USER_ATTR];
}
throw new apiAuthException("No user_id in token");
}
/**
* Returns attributes from the login ticket. This can contain
* various information about the user session.
*/
public function getAttributes() {
return array("envelope" => $this->envelope, "payload" => $this->payload);
}
}

View File

@ -0,0 +1,250 @@
<?php
/*
* Copyright 2008 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
require_once "external/OAuth.php";
/**
* Authentication class that deals with 3-Legged OAuth 1.0a authentication
*
* This class uses the OAuth 1.0a spec which has a slightly different work flow in
* how callback urls, request & access tokens are dealt with to prevent a possible
* man in the middle attack.
*
* @author Chris Chabot <chabotc@google.com>
*
*/
class apiOAuth extends apiAuth {
public $cacheKey;
protected $consumerToken;
protected $accessToken;
protected $privateKeyFile;
protected $developerKey;
public $service;
/**
* Instantiates the class, but does not initiate the login flow, leaving it
* to the discretion of the caller.
*/
public function __construct() {
global $apiConfig;
if (!empty($apiConfig['developer_key'])) {
$this->setDeveloperKey($apiConfig['developer_key']);
}
$this->consumerToken = new apiClientOAuthConsumer($apiConfig['oauth_consumer_key'], $apiConfig['oauth_consumer_secret'], NULL);
$this->signatureMethod = new apiClientOAuthSignatureMethod_HMAC_SHA1();
$this->cacheKey = 'OAuth:' . $apiConfig['oauth_consumer_key']; // Scope data to the local user as well, or else multiple local users will share the same OAuth credentials.
}
/**
* The 3 legged oauth class needs a way to store the access key and token
* it uses the apiCache class to do so.
*
* Constructing this class will initiate the 3 legged oauth work flow, including redirecting
* to the OAuth provider's site if required(!)
*
* @param string $consumerKey
* @param string $consumerSecret
* @return apiOAuth3Legged the logged-in provider instance
*/
public function authenticate($service) {
global $apiConfig;
$this->service = $service;
$this->service['authorization_token_url'] .= '?scope=' . apiClientOAuthUtil::urlencodeRFC3986($service['scope']) . '&domain=' . apiClientOAuthUtil::urlencodeRFC3986($apiConfig['site_name']) . '&oauth_token=';
if (isset($_GET['oauth_verifier']) && isset($_GET['oauth_token']) && isset($_GET['uid'])) {
$uid = $_GET['uid'];
$secret = apiClient::$cache->get($this->cacheKey.":nonce:" . $uid);
apiClient::$cache->delete($this->cacheKey.":nonce:" . $uid);
$token = $this->upgradeRequestToken($_GET['oauth_token'], $secret, $_GET['oauth_verifier']);
return json_encode($token);
} else {
// Initialize the OAuth dance, first request a request token, then kick the client to the authorize URL
// First we store the current URL in our cache, so that when the oauth dance is completed we can return there
$callbackUrl = ((isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on') ? 'https://' : 'http://') . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
$uid = uniqid();
$token = $this->obtainRequestToken($callbackUrl, $uid);
apiClient::$cache->set($this->cacheKey.":nonce:" . $uid, $token->secret);
$this->redirectToAuthorization($token);
}
}
/**
* Sets the internal oauth access token (which is returned by the authenticate function), a user should only
* go through the authenticate() flow once (which involces a bunch of browser redirections and authentication screens, not fun)
* and every time the user comes back the access token from the authentication() flow should be re-used (it essentially never expires)
* @param object $accessToken
*/
public function setAccessToken($accessToken) {
$accessToken = json_decode($accessToken, true);
if ($accessToken == null) {
throw new apiAuthException("Could not json decode the access token");
}
if (! isset($accessToken['key']) || ! isset($accessToken['secret'])) {
throw new apiAuthException("Invalid OAuth token, missing key and/or secret");
}
$this->accessToken = new apiClientOAuthConsumer($accessToken['key'], $accessToken['secret']);
}
/**
* Returns the current access token
*/
public function getAccessToken() {
return $this->accessToken;
}
/**
* Set the developer key to use, these are obtained through the API Console
*/
public function setDeveloperKey($developerKey) {
$this->developerKey = $developerKey;
}
/**
* Upgrades an existing request token to an access token.
*
* @param apiCache $cache cache class to use (file,apc,memcache,mysql)
* @param oauthVerifier
*/
public function upgradeRequestToken($requestToken, $requestTokenSecret, $oauthVerifier) {
$ret = $this->requestAccessToken($requestToken, $requestTokenSecret, $oauthVerifier);
$matches = array();
@parse_str($ret, $matches);
if (!isset($matches['oauth_token']) || !isset($matches['oauth_token_secret'])) {
throw new apiAuthException("Error authorizing access key (result was: {$ret})");
}
// The token was upgraded to an access token, we can now continue to use it.
$this->accessToken = new apiClientOAuthConsumer(apiClientOAuthUtil::urldecodeRFC3986($matches['oauth_token']), apiClientOAuthUtil::urldecodeRFC3986($matches['oauth_token_secret']));
return $this->accessToken;
}
/**
* Sends the actual request to exchange an existing request token for an access token.
*
* @param string $requestToken the existing request token
* @param string $requestTokenSecret the request token secret
* @return array('http_code' => HTTP response code (200, 404, 401, etc), 'data' => the html document)
*/
protected function requestAccessToken($requestToken, $requestTokenSecret, $oauthVerifier) {
$accessToken = new apiClientOAuthConsumer($requestToken, $requestTokenSecret);
$accessRequest = apiClientOAuthRequest::from_consumer_and_token($this->consumerToken, $accessToken, "GET", $this->service['access_token_url'], array('oauth_verifier' => $oauthVerifier));
$accessRequest->sign_request($this->signatureMethod, $this->consumerToken, $accessToken);
$request = apiClient::$io->makeRequest(new apiHttpRequest($accessRequest));
if ($request->getResponseHttpCode() != 200) {
throw new apiAuthException("Could not fetch access token, http code: " . $request->getResponseHttpCode() . ', response body: '. $request->getResponseBody());
}
return $request->getResponseBody();
}
/**
* Obtains a request token from the specified provider.
*/
public function obtainRequestToken($callbackUrl, $uid) {
$callbackParams = (strpos($_SERVER['REQUEST_URI'], '?') !== false ? '&' : '?') . 'uid=' . urlencode($uid);
$ret = $this->requestRequestToken($callbackUrl . $callbackParams);
$matches = array();
preg_match('/oauth_token=(.*)&oauth_token_secret=(.*)&oauth_callback_confirmed=(.*)/', $ret, $matches);
if (!is_array($matches) || count($matches) != 4) {
throw new apiAuthException("Error retrieving request key ({$ret})");
}
return new apiClientOAuthToken(apiClientOAuthUtil::urldecodeRFC3986($matches[1]), apiClientOAuthUtil::urldecodeRFC3986($matches[2]));
}
/**
* Sends the actual request to obtain a request token.
*
* @return array('http_code' => HTTP response code (200, 404, 401, etc), 'data' => the html document)
*/
protected function requestRequestToken($callbackUrl) {
$requestTokenRequest = apiClientOAuthRequest::from_consumer_and_token($this->consumerToken, NULL, "GET", $this->service['request_token_url'], array());
$requestTokenRequest->set_parameter('scope', $this->service['scope']);
$requestTokenRequest->set_parameter('oauth_callback', $callbackUrl);
$requestTokenRequest->sign_request($this->signatureMethod, $this->consumerToken, NULL);
$request = apiClient::$io->makeRequest(new apiHttpRequest($requestTokenRequest));
if ($request->getResponseHttpCode() != 200) {
throw new apiAuthException("Couldn't fetch request token, http code: " . $request->getResponseHttpCode() . ', response body: '. $request->getResponseBody());
}
return $request->getResponseBody();
}
/**
* Redirect the uset to the (provider's) authorize page, if approved it should kick the user back to the call back URL
* which hopefully means we'll end up in the constructor of this class again, but with oauth_continue=1 set
*
* @param OAuthToken $token the request token
* @param string $callbackUrl the URL to return to post-authorization (passed to login site)
*/
public function redirectToAuthorization($token) {
$authorizeRedirect = $this->service['authorization_token_url']. $token->key;
header("Location: $authorizeRedirect");
}
/**
* Sign the request using OAuth. This uses the consumer token and key
*
* @param string $method the method (get/put/delete/post)
* @param string $url the url to sign (http://site/social/rest/people/1/@me)
* @param array $params the params that should be appended to the url (count=20 fields=foo, etc)
* @param string $postBody for POST/PUT requests, the postBody is included in the signature
* @return string the signed url
*/
public function sign(apiHttpRequest $request) {
// add the developer key to the request before signing it
if ($this->developerKey) {
$request->setUrl($request->getUrl() . ((strpos($request->getUrl(), '?') === false) ? '?' : '&') . 'key='.urlencode($this->developerKey));
}
// and sign the request
$oauthRequest = apiClientOAuthRequest::from_request($request->getMethod(), $request->getBaseUrl(), $request->getQueryParams());
$params = $this->mergeParameters($request->getQueryParams());
foreach ($params as $key => $val) {
if (is_array($val)) {
$val = implode(',', $val);
}
$oauthRequest->set_parameter($key, $val);
}
$oauthRequest->sign_request($this->signatureMethod, $this->consumerToken, $this->accessToken);
$authHeaders = $oauthRequest->to_header();
$headers = $request->getHeaders();
$headers[] = $authHeaders;
$request->setHeaders($headers);
// and add the access token key to it (since it doesn't include the secret, it's still secure to store this in cache)
$request->accessKey = $this->accessToken->key;
return $request;
}
/**
* Merges the supplied parameters with reasonable defaults for 2 legged oauth. User-supplied parameters
* will have precedent over the defaults.
*
* @param array $params the user-supplied params that will be appended to the url
* @return array the combined parameters
*/
protected function mergeParameters($params) {
$defaults = array(
'oauth_nonce' => md5(microtime() . mt_rand()),
'oauth_version' => apiClientOAuthRequest::$version, 'oauth_timestamp' => time(),
'oauth_consumer_key' => $this->consumerToken->key
);
if ($this->accessToken != null) {
$params['oauth_token'] = $this->accessToken->key;
}
return array_merge($defaults, $params);
}
public function createAuthUrl($scope) {return null;}
public function refreshToken($refreshToken) {/* noop*/}
public function revokeToken() {/* noop*/}
}

View File

@ -0,0 +1,394 @@
<?php
/*
* Copyright 2008 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
require_once "apiVerifier.php";
require_once "apiLoginTicket.php";
require_once "service/apiUtils.php";
/**
* Authentication class that deals with the OAuth 2 web-server authentication flow
*
* @author Chris Chabot <chabotc@google.com>
* @author Chirag Shah <chirags@google.com>
*
*/
class apiOAuth2 extends apiAuth {
public $clientId;
public $clientSecret;
public $developerKey;
public $accessToken;
public $redirectUri;
public $state;
public $accessType = 'offline';
public $approvalPrompt = 'force';
const OAUTH2_REVOKE_URI = 'https://accounts.google.com/o/oauth2/revoke';
const OAUTH2_TOKEN_URI = 'https://accounts.google.com/o/oauth2/token';
const OAUTH2_AUTH_URL = 'https://accounts.google.com/o/oauth2/auth';
const OAUTH2_FEDERATED_SIGNON_CERTS_URL = 'https://www.googleapis.com/oauth2/v1/certs';
const CLOCK_SKEW_SECS = 300; // five minutes in seconds
const AUTH_TOKEN_LIFETIME_SECS = 300; // five minutes in seconds
const MAX_TOKEN_LIFETIME_SECS = 86400; // one day in seconds
/**
* Instantiates the class, but does not initiate the login flow, leaving it
* to the discretion of the caller (which is done by calling authenticate()).
*/
public function __construct() {
global $apiConfig;
if (! empty($apiConfig['developer_key'])) {
$this->developerKey = $apiConfig['developer_key'];
}
if (! empty($apiConfig['oauth2_client_id'])) {
$this->clientId = $apiConfig['oauth2_client_id'];
}
if (! empty($apiConfig['oauth2_client_secret'])) {
$this->clientSecret = $apiConfig['oauth2_client_secret'];
}
if (! empty($apiConfig['oauth2_redirect_uri'])) {
$this->redirectUri = $apiConfig['oauth2_redirect_uri'];
}
if (! empty($apiConfig['oauth2_access_type'])) {
$this->accessType = $apiConfig['oauth2_access_type'];
}
if (! empty($apiConfig['oauth2_approval_prompt'])) {
$this->approvalPrompt = $apiConfig['oauth2_approval_prompt'];
}
}
/**
* @param $service
* @return string
* @throws apiAuthException
*/
public function authenticate($service) {
if (isset($_GET['code'])) {
// We got here from the redirect from a successful authorization grant, fetch the access token
$request = apiClient::$io->makeRequest(new apiHttpRequest(self::OAUTH2_TOKEN_URI, 'POST', array(), array(
'code' => $_GET['code'],
'grant_type' => 'authorization_code',
'redirect_uri' => $this->redirectUri,
'client_id' => $this->clientId,
'client_secret' => $this->clientSecret
)));
if ($request->getResponseHttpCode() == 200) {
$this->setAccessToken($request->getResponseBody());
$this->accessToken['created'] = time();
return $this->getAccessToken();
} else {
$response = $request->getResponseBody();
$decodedResponse = json_decode($response, true);
if ($decodedResponse != $response && $decodedResponse != null && $decodedResponse['error']) {
$response = $decodedResponse['error'];
}
throw new apiAuthException("Error fetching OAuth2 access token, message: '$response'", $request->getResponseHttpCode());
}
}
$authUrl = $this->createAuthUrl($service['scope']);
header('Location: ' . $authUrl);
}
/**
* Create a URL to obtain user authorization.
* The authorization endpoint allows the user to first
* authenticate, and then grant/deny the access request.
* @param string $scope The scope is expressed as a list of space-delimited strings.
* @return string
*/
public function createAuthUrl($scope) {
$params = array(
'response_type=code',
'redirect_uri=' . urlencode($this->redirectUri),
'client_id=' . urlencode($this->clientId),
'scope=' . urlencode($scope),
'access_type=' . urlencode($this->accessType),
'approval_prompt=' . urlencode($this->approvalPrompt)
);
if (isset($this->state)) {
$params[] = 'state=' . urlencode($this->state);
}
$params = implode('&', $params);
return self::OAUTH2_AUTH_URL . "?$params";
}
/**
* @param $accessToken
* @throws apiAuthException Thrown when $accessToken is invalid.
*/
public function setAccessToken($accessToken) {
$accessToken = json_decode($accessToken, true);
if ($accessToken == null) {
throw new apiAuthException('Could not json decode the access token');
}
if (! isset($accessToken['access_token'])) {
throw new apiAuthException("Invalid token format");
}
$this->accessToken = $accessToken;
}
public function getAccessToken() {
return json_encode($this->accessToken);
}
public function setDeveloperKey($developerKey) {
$this->developerKey = $developerKey;
}
public function setState($state) {
$this->state = $state;
}
public function setAccessType($accessType) {
$this->accessType = $accessType;
}
public function setApprovalPrompt($approvalPrompt) {
$this->approvalPrompt = $approvalPrompt;
}
/**
* Include an accessToken in a given apiHttpRequest.
* @param apiHttpRequest $request
* @return apiHttpRequest
* @throws apiAuthException
*/
public function sign(apiHttpRequest $request) {
// add the developer key to the request before signing it
if ($this->developerKey) {
$requestUrl = $request->getUrl();
$requestUrl .= (strpos($request->getUrl(), '?') === false) ? '?' : '&';
$requestUrl .= 'key=' . urlencode($this->developerKey);
$request->setUrl($requestUrl);
}
// Cannot sign the request without an OAuth access token.
if (null == $this->accessToken) {
return $request;
}
// If the token is set to expire in the next 30 seconds (or has already
// expired), refresh it and set the new token.
$expired = ($this->accessToken['created'] + ($this->accessToken['expires_in'] - 30)) < time();
if ($expired) {
if (! array_key_exists('refresh_token', $this->accessToken)) {
throw new apiAuthException("The OAuth 2.0 access token has expired, "
. "and a refresh token is not available. Refresh tokens are not "
. "returned for responses that were auto-approved.");
}
$this->refreshToken($this->accessToken['refresh_token']);
}
// Add the OAuth2 header to the request
$request->setRequestHeaders(
array('Authorization' => 'Bearer ' . $this->accessToken['access_token'])
);
return $request;
}
/**
* Fetches a fresh access token with the given refresh token.
* @param string $refreshToken
* @return void
*/
public function refreshToken($refreshToken) {
$params = array(
'client_id' => $this->clientId,
'client_secret' => $this->clientSecret,
'refresh_token' => $refreshToken,
'grant_type' => 'refresh_token'
);
$request = apiClient::$io->makeRequest(
new apiHttpRequest(self::OAUTH2_TOKEN_URI, 'POST', array(), $params));
$code = $request->getResponseHttpCode();
$body = $request->getResponseBody();
if ($code == 200) {
$token = json_decode($body, true);
if ($token == null) {
throw new apiAuthException("Could not json decode the access token");
}
if (! isset($token['access_token']) || ! isset($token['expires_in'])) {
throw new apiAuthException("Invalid token format");
}
$this->accessToken['access_token'] = $token['access_token'];
$this->accessToken['expires_in'] = $token['expires_in'];
$this->accessToken['created'] = time();
} else {
throw new apiAuthException("Error refreshing the OAuth2 token, message: '$body'", $code);
}
}
/**
* Revoke an OAuth2 access token or refresh token. This method will revoke the current access
* token, if a token isn't provided.
* @throws apiAuthException
* @param string|null $token The token (access token or a refresh token) that should be revoked.
* @return boolean Returns True if the revocation was successful, otherwise False.
*/
public function revokeToken($token = null) {
if (!$token) {
$token = $this->accessToken['access_token'];
}
$request = new apiHttpRequest(self::OAUTH2_REVOKE_URI, 'POST', array(), "token=$token");
$response = apiClient::$io->makeRequest($request);
$code = $response->getResponseHttpCode();
if ($code == 200) {
$this->accessToken = null;
return true;
}
return false;
}
// Gets federated sign-on certificates to use for verifying identity tokens.
// Returns certs as array structure, where keys are key ids, and values
// are PEM encoded certificates.
private function getFederatedSignOnCerts() {
// This relies on makeRequest caching certificate responses.
$request = apiClient::$io->makeRequest(new apiHttpRequest(
self::OAUTH2_FEDERATED_SIGNON_CERTS_URL));
if ($request->getResponseHttpCode() == 200) {
$certs = json_decode($request->getResponseBody(), true);
if ($certs) {
return $certs;
}
}
throw new apiAuthException(
"Failed to retrieve verification certificates: '" .
$request->getResponseBody() . "'.",
$request->getResponseHttpCode());
}
/**
* Verifies an id token and returns the authenticated apiLoginTicket.
* Throws an exception if the id token is not valid.
* The audience parameter can be used to control which id tokens are
* accepted. By default, the id token must have been issued to this OAuth2 client.
*
* @param $id_token
* @param $audience
* @return apiLoginTicket
*/
public function verifyIdToken($id_token = null, $audience = null) {
if (!$id_token) {
$id_token = $this->accessToken['id_token'];
}
$certs = $this->getFederatedSignonCerts();
if (!$audience) {
$audience = $this->clientId;
}
return $this->verifySignedJwtWithCerts($id_token, $certs, $audience);
}
// Verifies the id token, returns the verified token contents.
// Visible for testing.
function verifySignedJwtWithCerts($jwt, $certs, $required_audience) {
$segments = explode(".", $jwt);
if (count($segments) != 3) {
throw new apiAuthException("Wrong number of segments in token: $jwt");
}
$signed = $segments[0] . "." . $segments[1];
$signature = apiUtils::urlSafeB64Decode($segments[2]);
// Parse envelope.
$envelope = json_decode(apiUtils::urlSafeB64Decode($segments[0]), true);
if (!$envelope) {
throw new apiAuthException("Can't parse token envelope: " . $segments[0]);
}
// Parse token
$json_body = apiUtils::urlSafeB64Decode($segments[1]);
$payload = json_decode($json_body, true);
if (!$payload) {
throw new apiAuthException("Can't parse token payload: " . $segments[1]);
}
// Check signature
$verified = false;
foreach ($certs as $keyName => $pem) {
$public_key = new apiPemVerifier($pem);
if ($public_key->verify($signed, $signature)) {
$verified = true;
break;
}
}
if (!$verified) {
throw new apiAuthException("Invalid token signature: $jwt");
}
// Check issued-at timestamp
$iat = 0;
if (array_key_exists("iat", $payload)) {
$iat = $payload["iat"];
}
if (!$iat) {
throw new apiAuthException("No issue time in token: $json_body");
}
$earliest = $iat - self::CLOCK_SKEW_SECS;
// Check expiration timestamp
$now = time();
$exp = 0;
if (array_key_exists("exp", $payload)) {
$exp = $payload["exp"];
}
if (!$exp) {
throw new apiAuthException("No expiration time in token: $json_body");
}
if ($exp >= $now + self::MAX_TOKEN_LIFETIME_SECS) {
throw new apiAuthException(
"Expiration time too far in future: $json_body");
}
$latest = $exp + self::CLOCK_SKEW_SECS;
if ($now < $earliest) {
throw new apiAuthException(
"Token used too early, $now < $earliest: $json_body");
}
if ($now > $latest) {
throw new apiAuthException(
"Token used too late, $now > $latest: $json_body");
}
// TODO(beaton): check issuer field?
// Check audience
$aud = $payload["aud"];
if ($aud != $required_audience) {
throw new apiAuthException("Wrong recipient, $aud != $required_audience: $json_body");
}
// All good.
return new apiLoginTicket($envelope, $payload);
}
}

View File

@ -0,0 +1,66 @@
<?php
/*
* Copyright 2011 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* Signs data.
*
* Only used for testing.
*
* @author Brian Eaton <beaton@google.com>
*/
class apiP12Signer extends apiSigner {
// OpenSSL private key resource
private $privateKey;
// Creates a new signer from a .p12 file.
function __construct($p12file, $password) {
if (!function_exists('openssl_x509_read')) {
throw new Exception(
'The Google PHP API library needs the openssl PHP extension');
}
// This throws on error
$p12 = file_get_contents($p12file);
$certs = array();
if (!openssl_pkcs12_read($p12, $certs, $password)) {
throw new apiAuthException("Unable to parse $p12file. " .
"Is this a .p12 file? Is the password correct? OpenSSL error: " .
openssl_error_string());
}
// TODO(beaton): is this part of the contract for the openssl_pkcs12_read
// method? What happens if there are multiple private keys? Do we care?
if (!array_key_exists("pkey", $certs) || !$certs["pkey"]) {
throw new apiAuthException("No private key found in p12 file $p12file");
}
$this->privateKey = openssl_pkey_get_private($certs["pkey"]);
if (!$this->privateKey) {
throw new apiAuthException("Unable to load private key in $p12file");
}
}
function __destruct() {
if ($this->privateKey) {
openssl_pkey_free($this->privateKey);
}
}
function sign($data) {
if (!openssl_sign($data, $signature, $this->privateKey, "sha256")) {
throw new apiAuthException("Unable to sign data");
}
return $signature;
}
}

View File

@ -0,0 +1,61 @@
<?php
/*
* Copyright 2011 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* Verifies signatures using PEM encoded certificates.
*
* @author Brian Eaton <beaton@google.com>
*/
class apiPemVerifier extends apiVerifier {
private $publicKey;
/**
* Constructs a verifier from the supplied PEM-encoded certificate.
*
* $pem: a PEM encoded certificate (not a file).
*/
function __construct($pem) {
if (!function_exists('openssl_x509_read')) {
throw new Exception(
'The Google PHP API library needs the openssl PHP extension');
}
$this->publicKey = openssl_x509_read($pem);
if (!$this->publicKey) {
throw new apiAuthException("Unable to parse PEM: $pem");
}
}
function __destruct() {
if ($this->publicKey) {
openssl_x509_free($this->publicKey);
}
}
/**
* Verifies the signature on data.
*
* Returns true if the signature is valid, false otherwise.
*/
function verify($data, $signature) {
$status = openssl_verify($data, $signature, $this->publicKey, "sha256");
if ($status === -1) {
throw new apiAuthException("Signature verification error: " .
openssl_error_string());
}
return $status === 1;
}
}

View File

@ -0,0 +1,30 @@
<?php
/*
* Copyright 2011 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
require_once "apiP12Signer.php";
/**
* Signs data.
*
* @author Brian Eaton <beaton@google.com>
*/
abstract class apiSigner {
/**
* Signs data, returns the signature as binary data.
*/
abstract public function sign($data);
}

View File

@ -0,0 +1,31 @@
<?php
/*
* Copyright 2011 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
require_once "apiPemVerifier.php";
/**
* Verifies signatures.
*
* @author Brian Eaton <beaton@google.com>
*/
abstract class apiVerifier {
/**
* Checks a signature, returns true if the signature is correct,
* false otherwise.
*/
abstract public function verify($data, $signature);
}