Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings
This repository was archived by the owner on Jan 13, 2020. It is now read-only.

Commit fa295d0

Browse files
author
Jim
committed
Initial Commit
0 parents commit fa295d0

File tree

6 files changed

+1102
-0
lines changed

6 files changed

+1102
-0
lines changed

‎README‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
Replace all of the TODO information with their appropriate values. Check the code comments for what to put in each. Make sure you change the callback URL in index.php to reflect your server setup. In this example the callback needs to point to the authorize.php file.
2+
3+
key = Your OAuth Consumer key
4+
secret = Your OAuth Consumer secret
5+
apikey = Your YouTube api key
6+
callback = The location of authorize.php on your server (mine happens to be: http://localhost/youtube_api/authorize.php
7+
8+
After you have all the appropriate values entered or changed then you can visit index.php and click the link. You will be redirected to Google to verify your application. After that you are redirected to authorize.php which will finish the OAuth authentication and instantiate the YouTube api with your new access token values. The YouTube api can then make authenticated calls.
9+
10+
It's worth mentioning that OAuth v1 access tokens don't expire so you only need your users to authenticate with your application once. Store the access token data in your database. Then retrieve it from the database next time you need to make a call. The example code is purely academic in regards to authenticating with YouTube.

‎api/google_oauth.php‎

Lines changed: 184 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,184 @@
1+
<?php
2+
/*
3+
Copyright (C) 2011 by Jim Saunders
4+
5+
Permission is hereby granted, free of charge, to any person obtaining a copy
6+
of this software and associated documentation files (the "Software"), to deal
7+
in the Software without restriction, including without limitation the rights
8+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9+
copies of the Software, and to permit persons to whom the Software is
10+
furnished to do so, subject to the following conditions:
11+
12+
The above copyright notice and this permission notice shall be included in
13+
all copies or substantial portions of the Software.
14+
15+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21+
THE SOFTWARE.
22+
*/
23+
24+
require_once 'oauth_helper.php';
25+
26+
/**
27+
* This library is meant to get you an oauth access token
28+
* for a google service. You can define which service by
29+
* changing the SCOPE constant. You will need to pass in
30+
* your consumer key and secret upon loading this library.
31+
*
32+
* I currently use it in my YouTube API but it can be used
33+
* for any google service that allows for OAuth.
34+
*/
35+
class google_oauth
36+
{
37+
const SCHEME = 'https';
38+
const HOST = 'www.google.com';
39+
const AUTHORIZE_URI = '/accounts/OAuthAuthorizeToken';
40+
const REQUEST_URI = '/accounts/OAuthGetRequestToken';
41+
const ACCESS_URI = '/accounts/OAuthGetAccessToken';
42+
43+
//This should be changed to correspond with the
44+
//google service you are authenticating against.
45+
const SCOPE = 'https://gdata.youtube.com'; //YouTube
46+
47+
//Set this flag to true for detailed logging.
48+
const DEBUG = false;
49+
50+
//Array that should contain the consumer secret and
51+
//key which should be passed into the constructor.
52+
private $_consumer = false;
53+
54+
/**
55+
* Pass in the key and secret given to you by google
56+
* Note that the secret should either be a hash string for
57+
* HMAC signatures or a file path string for RSA signatures.
58+
*
59+
* @param string $key The oauth key given to you by google
60+
* @param string $secret The hash given to you by google or a path to your RSA sig file
61+
* @param (Optional) array $params Lets you change things like the signing algorithm
62+
*/
63+
public function __construct($key, $secret, array $params = array())
64+
{
65+
$params['key'] = $key;
66+
$params['secret'] = $secret;
67+
//Set defaults for method and algorithm if they are not specified
68+
if(!array_key_exists('method', $params))$params['method'] = 'GET';
69+
if(!array_key_exists('algorithm', $params))$params['algorithm'] = OAUTH_ALGORITHMS::HMAC_SHA1;
70+
71+
$this->_consumer = $params;
72+
}
73+
74+
/**
75+
* This is called to begin the oauth token exchange. This should only
76+
* need to be called once for a user, provided they allow oauth access.
77+
* It will return a URL that your site should redirect to, allowing the
78+
* user to login and accept your application.
79+
*
80+
* @param string $callback the page on your site you wish to return to
81+
* after the user grants your application access.
82+
* @return mixed either the URL to redirect to, or if they specified HMAC
83+
* signing an array with the token_secret and the redirect url
84+
*/
85+
public function get_request_token($callback)
86+
{
87+
$baseurl = self::SCHEME.'://'.self::HOST.self::REQUEST_URI;
88+
89+
//Generate an array with the initial oauth values we need
90+
$auth = build_auth_array($baseurl, $this->_consumer['key'], $this->_consumer['secret'],
91+
array('oauth_callback'=>urlencode($callback), 'scope'=>urlencode(self::SCOPE)),
92+
$this->_consumer['method'], $this->_consumer['algorithm']);
93+
//Create the "Authorization" portion of the header
94+
$str = '';
95+
foreach($auth AS $key=>$value)
96+
if($key != 'scope')$str .= ",{$key}=\"{$value}\"";//Do not include scope in the Authorization string.
97+
$str = substr($str, 1);
98+
$str = 'Authorization: OAuth '.$str;
99+
//Send it
100+
$response = $this->_connect("{$baseurl}?scope={$auth['scope']}", $str);
101+
//We should get back a request token and secret which
102+
//we will add to the redirect url.
103+
parse_str($response, $resarray);
104+
//Return the full redirect url and let the user decide what to do from there.
105+
$redirect = self::SCHEME.'://'.self::HOST.self::AUTHORIZE_URI."?oauth_token={$resarray['oauth_token']}";
106+
//If they are using HMAC then we need to return the token secret for them to store.
107+
if($this->_consumer['algorithm'] == OAUTH_ALGORITHMS::RSA_SHA1)return $redirect;
108+
else return array('token_secret'=>$resarray['oauth_token_secret'], 'redirect'=>$redirect);
109+
}
110+
111+
/**
112+
* This is called to finish the oauth token exchange. This too should
113+
* only need to be called once for a user. The token returned should
114+
* be stored in your database for that particular user.
115+
*
116+
* @param string $token this is the oauth_token returned with your callback url
117+
* @param string $secret this is the token secret supplied from the request (Only required if using HMAC)
118+
* @param string $verifier this is the oauth_verifier returned with your callback url
119+
* @return array access token and token secret
120+
*/
121+
public function get_access_token($token = false, $secret = false, $verifier = false)
122+
{
123+
//If no request token was specified then attempt to get one from the url
124+
if($token === false && isset($_GET['oauth_token']))$token = $_GET['oauth_token'];
125+
if($verifier === false && isset($_GET['oauth_verifier']))$verifier = $_GET['oauth_verifier'];
126+
//If all else fails attempt to get it from the request uri.
127+
if($token === false && $verifier === false)
128+
{
129+
$uri = $_SERVER['REQUEST_URI'];
130+
$uriparts = explode('?', $uri);
131+
132+
$authfields = array();
133+
parse_str($uriparts[1], $authfields);
134+
$token = $authfields['oauth_token'];
135+
$verifier = $authfields['oauth_verifier'];
136+
}
137+
138+
$tokenddata = array('oauth_token'=>urlencode($token), 'oauth_verifier'=>urlencode($verifier));
139+
if($secret !== false)$tokenddata['oauth_token_secret'] = urlencode($secret);
140+
141+
$baseurl = self::SCHEME.'://'.self::HOST.self::ACCESS_URI;
142+
//Include the token and verifier into the header request.
143+
$auth = get_auth_header($baseurl, $this->_consumer['key'], $this->_consumer['secret'],
144+
$tokenddata, $this->_consumer['method'], $this->_consumer['algorithm']);
145+
$response = $this->_connect($baseurl, $auth);
146+
//Parse the response into an array it should contain
147+
//both the access token and the secret key. (You only
148+
//need the secret key if you use HMAC-SHA1 signatures.)
149+
parse_str($response, $oauth);
150+
//Return the token and secret for storage
151+
return $oauth;
152+
}
153+
154+
/**
155+
* Connects to the server and sends the request,
156+
* then returns the response from the server.
157+
* @param <type> $url
158+
* @param <type> $auth
159+
* @return <type>
160+
*/
161+
private function _connect($url, $auth)
162+
{
163+
$ch = curl_init($url);
164+
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC ) ;
165+
curl_setopt($ch, CURLOPT_SSLVERSION,3);
166+
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
167+
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
168+
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
169+
curl_setopt($ch, CURLOPT_HTTPHEADER, explode("\r\n", $auth));
170+
curl_setopt($ch, CURLINFO_HEADER_OUT, true);
171+
172+
$response = curl_exec($ch);
173+
174+
if(self::DEBUG)
175+
{
176+
error_log(print_r(curl_getinfo($ch), true));
177+
error_log($response);
178+
}
179+
curl_close($ch);
180+
return $response;
181+
}
182+
}
183+
// ./system/application/libraries
184+
?>

‎api/oauth_helper.php‎

Lines changed: 177 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,177 @@
1+
<?php
2+
3+
/*
4+
Copyright (C) 2011 by Jim Saunders
5+
6+
Permission is hereby granted, free of charge, to any person obtaining a copy
7+
of this software and associated documentation files (the "Software"), to deal
8+
in the Software without restriction, including without limitation the rights
9+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10+
copies of the Software, and to permit persons to whom the Software is
11+
furnished to do so, subject to the following conditions:
12+
13+
The above copyright notice and this permission notice shall be included in
14+
all copies or substantial portions of the Software.
15+
16+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
22+
THE SOFTWARE.
23+
*/
24+
25+
/**
26+
* Defines the different OAuth Signing algorithms. You
27+
* should use this instead of writing them out each time.
28+
*/
29+
class OAUTH_ALGORITHMS
30+
{
31+
const HMAC_SHA1 = 'HMAC-SHA1';
32+
const RSA_SHA1 = 'RSA-SHA1';
33+
}
34+
35+
/**
36+
* Signs an array of oauth parameters according to the 1.0 spec using
37+
* the hmac-sha1 hasing algorithm
38+
*
39+
* @param string $method either GET or POST
40+
* @param string $baseurl the baseurl we are authenticating againts
41+
* @param string $secret the consumer secret key
42+
* @param array $parameters all parameters that need to be signed (NOTE: the token secret key should be added here)
43+
* @return string the signature
44+
*/
45+
function sign_hmac_sha1($method, $baseurl, $secret, array $parameters)
46+
{
47+
$data = $method.'&';
48+
$data .= urlencode($baseurl).'&';
49+
$oauth = '';
50+
ksort($parameters);
51+
//Put the token secret in if it does not exist. It
52+
//will be empty if it does not exist as per the spec.
53+
if(!array_key_exists('oauth_token_secret', $parameters))$parameters['oauth_token_secret'] = '';
54+
foreach($parameters as $key => $value)
55+
{
56+
//Don't include the token secret into the base string
57+
if(strtolower($key) != 'oauth_token_secret')$oauth .= "&{$key}={$value}";
58+
}
59+
$data .= urlencode(substr($oauth, 1));
60+
$secret .= '&'.$parameters['oauth_token_secret'];
61+
62+
return base64_encode(hash_hmac('sha1', $data, $secret, true));
63+
}
64+
65+
/**
66+
* Signs an array of oauth parameters according to the 1.0 spec using
67+
* the rsa-sha1 hasing algorithm
68+
*
69+
* @param string $method either GET or POST
70+
* @param string $baseurl the baseurl we are authenticating againts
71+
* @param string $certfile the location of your private certificate file
72+
* @param array $parameters all parameters that need to be signed
73+
* @return string the signature
74+
*/
75+
function sign_rsa_sha1($method, $baseurl, $certfile, array $parameters)
76+
{
77+
$fp = fopen($certfile, "r");
78+
$private = fread($fp, 8192);
79+
fclose($fp);
80+
81+
$data = $method.'&';
82+
$data .= urlencode($baseurl).'&';
83+
$oauth = '';
84+
ksort($parameters);
85+
86+
foreach($parameters as $key => $value)
87+
$oauth .= "&{$key}={$value}";
88+
$data .= urlencode(substr($oauth, 1));
89+
90+
$keyid = openssl_get_privatekey($private);
91+
openssl_sign($data, $signature, $keyid);
92+
openssl_free_key($keyid);
93+
94+
return base64_encode($signature);
95+
}
96+
97+
/**
98+
* Assembles the auth params array into a string that can
99+
* be put into an http header request.
100+
*
101+
* @param array $authparams the oauth parameters
102+
* @return string the header authorization portion with trailing \r\n
103+
*/
104+
function build_auth_string(array $authparams)
105+
{
106+
$header = "Authorization: OAuth ";
107+
$auth = '';
108+
foreach($authparams AS $key=>$value)
109+
{
110+
//Don't include token secret
111+
if($key != 'oauth_token_secret')$auth .= ", {$key}=\"{$value}\"";
112+
}
113+
return $header.substr($auth, 2)."\r\n";
114+
}
115+
116+
/**
117+
* Assemble an associative array with oauth values
118+
*
119+
* @param string $baseurl the base url we are authenticating against.
120+
* @param string $key your consumer key
121+
* @param string $secret either your consumer secret key or the file location of your rsa private key.
122+
* @param array $extra additional oauth parameters that should be included (you must urlencode, if appropriate, before calling this function)
123+
* @param string $method either GET or POST
124+
* @param string $algo either HMAC-SHA1 or RSA-SHA1 (NOTE: this affects what you put in for the secret parameter)
125+
* @return array of all the oauth parameters
126+
*/
127+
function build_auth_array($baseurl, $key, $secret, $extra = array(), $method = 'GET', $algo = OAUTH_ALGORITHMS::RSA_SHA1)
128+
{
129+
$auth['oauth_consumer_key'] = $key;
130+
$auth['oauth_signature_method'] = $algo;
131+
$auth['oauth_timestamp'] = time();
132+
$auth['oauth_nonce'] = md5(uniqid(rand(), true));
133+
$auth['oauth_version'] = '1.0';
134+
135+
$auth = array_merge($auth, $extra);
136+
137+
//We want to remove any query parameters from the base url
138+
$urlsegs = explode("?", $baseurl);
139+
$baseurl = $urlsegs[0];
140+
141+
//If there are any query parameters we need to make sure they
142+
//get signed with the rest of the auth data.
143+
$signing = $auth;
144+
if(count($urlsegs) > 1)
145+
{
146+
preg_match_all("/([\w\-]+)\=([\w\d\-\%\.\$\+\*]+)\&?/", $urlsegs[1], $matches);
147+
$signing = $signing + array_combine($matches[1], $matches[2]);
148+
}
149+
150+
if(strtoupper($algo) == OAUTH_ALGORITHMS::HMAC_SHA1)$auth['oauth_signature'] = sign_hmac_sha1($method, $baseurl, $secret, $signing);
151+
else if(strtoupper($algo) == OAUTH_ALGORITHMS::RSA_SHA1)$auth['oauth_signature'] = sign_rsa_sha1 ($method, $baseurl, $secret, $signing);
152+
153+
$auth['oauth_signature'] = urlencode($auth['oauth_signature']);
154+
return $auth;
155+
}
156+
157+
/**
158+
* Creates the authorization portion of a header NOTE: This does not
159+
* create a complete http header. Also NOTE: the oauth_token parameter
160+
* should be passed in using the $extra array.
161+
*
162+
* @param string $baseurl the base url we are authenticating against.
163+
* @param string $key your consumer key
164+
* @param string $secret either your consumer secret key or the file location of your rsa private key.
165+
* @param array $extra additional oauth parameters that should be included (you must urlencode a parameter, if appropriate, before calling this function)
166+
* @param string $method either GET or POST
167+
* @param string $algo either HMAC-SHA1 or RSA-SHA1 (NOTE: this affects what you put in for the secret parameter)
168+
* @return string the header authorization portion with trailing \r\n
169+
*/
170+
function get_auth_header($baseurl, $key, $secret, $extra = array(), $method = 'GET', $algo = OAUTH_ALGORITHMS::RSA_SHA1)
171+
{
172+
$auth = build_auth_array($baseurl, $key, $secret, $extra, $method, $algo);
173+
return build_auth_string($auth);
174+
}
175+
176+
/* ./application/helpers/oauth_helper.php */
177+
?>

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /