OAuth1.php 9.72 KB
Newer Older
1 2 3 4 5 6 7
<?php
/**
 * @link http://www.yiiframework.com/
 * @copyright Copyright (c) 2008 Yii Software LLC
 * @license http://www.yiiframework.com/license/
 */

8
namespace yii\authclient;
9 10 11 12 13

use yii\base\Exception;
use Yii;

/**
14
 * OAuth1 serves as a client for the OAuth 1/1.0a flow.
15 16 17 18
 *
 * In oder to acquire access token perform following sequence:
 *
 * ~~~
19
 * use yii\authclient\OAuth1;
20
 *
21
 * $oauthClient = new OAuth1();
22 23
 * $requestToken = $oauthClient->fetchRequestToken(); // Get request token
 * $url = $oauthClient->buildAuthUrl($requestToken); // Get authorization URL
24
 * return Yii::$app->getResponse()->redirect($url); // Redirect to authorization URL
25 26 27 28 29 30 31 32 33
 * // After user returns at our site:
 * $accessToken = $oauthClient->fetchAccessToken($requestToken); // Upgrade to access token
 * ~~~
 *
 * @see http://oauth.net/
 *
 * @author Paul Klimov <klimov.paul@gmail.com>
 * @since 2.0
 */
34
class OAuth1 extends BaseOAuth
35 36 37 38 39 40 41 42
{
	/**
	 * @var string protocol version.
	 */
	public $version = '1.0';
	/**
	 * @var string OAuth consumer key.
	 */
Paul Klimov committed
43
	public $consumerKey;
44 45 46
	/**
	 * @var string OAuth consumer secret.
	 */
Paul Klimov committed
47
	public $consumerSecret;
48 49 50
	/**
	 * @var string OAuth request token URL.
	 */
Paul Klimov committed
51
	public $requestTokenUrl;
52 53 54 55 56 57 58
	/**
	 * @var string request token HTTP method.
	 */
	public $requestTokenMethod = 'GET';
	/**
	 * @var string OAuth access token URL.
	 */
Paul Klimov committed
59
	public $accessTokenUrl;
60 61 62 63 64 65 66 67
	/**
	 * @var string access token HTTP method.
	 */
	public $accessTokenMethod = 'GET';

	/**
	 * Fetches the OAuth request token.
	 * @param array $params additional request params.
68
	 * @return OAuthToken request token.
69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90
	 */
	public function fetchRequestToken(array $params = [])
	{
		$this->removeState('token');
		$defaultParams = [
			'oauth_consumer_key' => $this->consumerKey,
			'oauth_callback' => $this->getReturnUrl(),
			//'xoauth_displayname' => Yii::$app->name,
		];
		if (!empty($this->scope)) {
			$defaultParams['scope'] = $this->scope;
		}
		$response = $this->sendSignedRequest($this->requestTokenMethod, $this->requestTokenUrl, array_merge($defaultParams, $params));
		$token = $this->createToken([
			'params' => $response
		]);
		$this->setState('requestToken', $token);
		return $token;
	}

	/**
	 * Composes user authorization URL.
91
	 * @param OAuthToken $requestToken OAuth request token.
92 93 94 95
	 * @param array $params additional request params.
	 * @return string authorize URL
	 * @throws Exception on failure.
	 */
96
	public function buildAuthUrl(OAuthToken $requestToken = null, array $params = [])
97 98 99 100 101 102 103 104 105 106 107 108 109
	{
		if (!is_object($requestToken)) {
			$requestToken = $this->getState('requestToken');
			if (!is_object($requestToken)) {
				throw new Exception('Request token is required to build authorize URL!');
			}
		}
		$params['oauth_token'] = $requestToken->getToken();
		return $this->composeUrl($this->authUrl, $params);
	}

	/**
	 * Fetches OAuth access token.
110
	 * @param OAuthToken $requestToken OAuth request token.
111 112
	 * @param string $oauthVerifier OAuth verifier.
	 * @param array $params additional request params.
113
	 * @return OAuthToken OAuth access token.
114 115
	 * @throws Exception on failure.
	 */
116
	public function fetchAccessToken(OAuthToken $requestToken = null, $oauthVerifier = null, array $params = [])
117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181
	{
		if (!is_object($requestToken)) {
			$requestToken = $this->getState('requestToken');
			if (!is_object($requestToken)) {
				throw new Exception('Request token is required to fetch access token!');
			}
		}
		$this->removeState('requestToken');
		$defaultParams = [
			'oauth_consumer_key' => $this->consumerKey,
			'oauth_token' => $requestToken->getToken()
		];
		if ($oauthVerifier === null) {
			if (isset($_REQUEST['oauth_verifier'])) {
				$oauthVerifier = $_REQUEST['oauth_verifier'];
			}
		}
		if (!empty($oauthVerifier)) {
			$defaultParams['oauth_verifier'] = $oauthVerifier;
		}
		$response = $this->sendSignedRequest($this->accessTokenMethod, $this->accessTokenUrl, array_merge($defaultParams, $params));

		$token = $this->createToken([
			'params' => $response
		]);
		$this->setAccessToken($token);
		return $token;
	}

	/**
	 * Sends HTTP request, signed by {@link signatureMethod}.
	 * @param string $method request type.
	 * @param string $url request URL.
	 * @param array $params request params.
	 * @return array response.
	 */
	protected function sendSignedRequest($method, $url, array $params = [])
	{
		$params = array_merge($params, $this->generateCommonRequestParams());
		$params = $this->signRequest($method, $url, $params);
		return $this->sendRequest($method, $url, $params);
	}

	/**
	 * Composes HTTP request CUrl options, which will be merged with the default ones.
	 * @param string $method request type.
	 * @param string $url request URL.
	 * @param array $params request params.
	 * @return array CUrl options.
	 * @throws Exception on failure.
	 */
	protected function composeRequestCurlOptions($method, $url, array $params)
	{
		$curlOptions = [];
		switch ($method) {
			case 'GET': {
				$curlOptions[CURLOPT_URL] = $this->composeUrl($url, $params);
				break;
			}
			case 'POST': {
				$curlOptions[CURLOPT_POST] = true;
				if (!empty($params)){
					$curlOptions[CURLOPT_POSTFIELDS] = $params;
				}
				$authorizationHeader = $this->composeAuthorizationHeader($params);
Paul Klimov committed
182
				if (!empty($authorizationHeader)) {
183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204
					$curlOptions[CURLOPT_HTTPHEADER] = ['Content-Type: application/atom+xml', $authorizationHeader];
				}
				break;
			}
			case 'HEAD':
			case 'PUT':
			case 'DELETE': {
				$curlOptions[CURLOPT_CUSTOMREQUEST] = $method;
				if (!empty($params)) {
					$curlOptions[CURLOPT_URL] = $this->composeUrl($url, $params);
				}
				break;
			}
			default: {
				throw new Exception("Unknown request method '{$method}'.");
			}
		}
		return $curlOptions;
	}

	/**
	 * Performs request to the OAuth API.
205
	 * @param OAuthToken $accessToken actual access token.
206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221
	 * @param string $url absolute API URL.
	 * @param string $method request method.
	 * @param array $params request parameters.
	 * @return array API response.
	 * @throws Exception on failure.
	 */
	protected function apiInternal($accessToken, $url, $method, array $params)
	{
		$params['oauth_consumer_key'] = $this->consumerKey;
		$params['oauth_token'] = $accessToken->getToken();
		$response = $this->sendSignedRequest($method, $url, $params);
		return $response;
	}

	/**
	 * Gets new auth token to replace expired one.
222 223
	 * @param OAuthToken $token expired auth token.
	 * @return OAuthToken new auth token.
224
	 */
225
	public function refreshAccessToken(OAuthToken $token)
226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300
	{
		// @todo
		return null;
	}

	/**
	 * Composes default {@link returnUrl} value.
	 * @return string return URL.
	 */
	protected function defaultReturnUrl()
	{
		$params = $_GET;
		unset($params['oauth_token']);
		return Yii::$app->getUrlManager()->createAbsoluteUrl(Yii::$app->controller->getRoute(), $params);
	}

	/**
	 * Generates nonce value.
	 * @return string nonce value.
	 */
	protected function generateNonce()
	{
		return md5(microtime() . mt_rand());
	}

	/**
	 * Generates timestamp.
	 * @return integer timestamp.
	 */
	protected function generateTimestamp()
	{
		return time();
	}

	/**
	 * Generate common request params like version, timestamp etc.
	 * @return array common request params.
	 */
	protected function generateCommonRequestParams()
	{
		$params = [
			'oauth_version' => $this->version,
			'oauth_nonce' => $this->generateNonce(),
			'oauth_timestamp' => $this->generateTimestamp(),
		];
		return $params;
	}

	/**
	 * Sign request with {@link signatureMethod}.
	 * @param string $method request method.
	 * @param string $url request URL.
	 * @param array $params request params.
	 * @return array signed request params.
	 */
	protected function signRequest($method, $url, array $params)
	{
		$signatureMethod = $this->getSignatureMethod();
		$params['oauth_signature_method'] = $signatureMethod->getName();
		$signatureBaseString = $this->composeSignatureBaseString($method, $url, $params);
		$signatureKey = $this->composeSignatureKey();
		$params['oauth_signature'] = $signatureMethod->generateSignature($signatureBaseString, $signatureKey);
		return $params;
	}

	/**
	 * Creates signature base string, which will be signed by {@link signatureMethod}.
	 * @param string $method request method.
	 * @param string $url request URL.
	 * @param array $params request params.
	 * @return string base signature string.
	 */
	protected function composeSignatureBaseString($method, $url, array $params)
	{
		unset($params['oauth_signature']);
301
		uksort($params, 'strcmp'); // Parameters are sorted by name, using lexicographical byte value ordering. Ref: Spec: 9.1.1
302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354
		$parts = [
			strtoupper($method),
			$url,
			http_build_query($params, '', '&', PHP_QUERY_RFC3986)
		];
		$parts = array_map('rawurlencode', $parts);
		return implode('&', $parts);
	}

	/**
	 * Composes request signature key.
	 * @return string signature key.
	 */
	protected function composeSignatureKey()
	{
		$signatureKeyParts = [
			$this->consumerSecret
		];
		$accessToken = $this->getAccessToken();
		if (is_object($accessToken)) {
			$signatureKeyParts[] = $accessToken->getTokenSecret();
		} else {
			$signatureKeyParts[] = '';
		}
		$signatureKeyParts = array_map('rawurlencode', $signatureKeyParts);
		return implode('&', $signatureKeyParts);
	}

	/**
	 * Composes authorization header content.
	 * @param array $params request params.
	 * @param string $realm authorization realm.
	 * @return string authorization header content.
	 */
	protected function composeAuthorizationHeader(array $params, $realm = '')
	{
		$header = 'Authorization: OAuth';
		$headerParams = [];
		if (!empty($realm)) {
			$headerParams[] = 'realm="' . rawurlencode($realm) . '"';
		}
		foreach ($params as $key => $value) {
			if (substr($key, 0, 5) != 'oauth') {
				continue;
			}
			$headerParams[] = rawurlencode($key) . '="' . rawurlencode($value) . '"';
		}
		if (!empty($headerParams)) {
			$header .= ' ' . implode(', ', $headerParams);
		}
		return $header;
	}
}