| Acquire an Access Token |
|
This is the explicit flow (serverside) implementation of OAuth 2.0.
This example is written in PHP, but OAuth is language-agnostic and will
work with any server side language.
Step 1: Send your website visitor to our authorization page along with a way to get back
GET Parameters:
- redirect_uri (Required)
- client_id (Required)
Step 2: Upon authorizing that your application can access their account,
they will be redirected to your redirect_uri and a code will be passed along as a
query string parameter
Step 3: Send a request to exchange the code and your client_secret for a
temporary access token, which can be used to access their account
POST Parameters:
- code (Required)
- Code Returned from End-user Authorization
- redirect_uri (Required)
- Same Redirect URI as Above
- client_id (Required)
- client_secret (Required)
Step 4: The website visitor is again redirected to your redirect_uri along with
an access token as a query string parameter
Connect to a live demo
|
<?php
// EXAMPLE OF OAUTH 2.0 EXPLICIT FLOW IMPLEMENTATION IN PHP
// Note that OAuth 2.0 can also be implemented clientside via javascript (see demo above)
$client_id = '';
$client_secret = '';
$current_url = 'http://'.$_SERVER['HTTP_HOST'].$_SERVER['PHP_SELF'];
if (isset($_REQUEST['access_token']) AND $access_token = $_REQUEST['access_token'])
{
// Pass your Access Token into all POST requests to authenticate yourself
echo 'Your Access Token for this session is ' . $access_token;
}
else
{
// Send your website visitor to our authorization page along with a way to get back
if (!isset($_REQUEST['code']))
{
header("Location: http://www.daniweb.com/api/oauth?client_id=$client_id&redirect_uri=".urlencode($current_url));
}
// Upon authorizing your access, they will be redirected to your redirect_uri
// and Code will be passed along as a query string parameter
// Initialize cURL to send a POST request
$ch = curl_init('http://www.daniweb.com/api/access_token');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, false);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_POST, true);
// Use the Code to acquire a temporary Access Token
// to use for the current session
// You can save the Code to retrieve a new Access Token
// when it expires (and invalidate the existing Access Token
// if it hasn't expired yet)
curl_setopt($ch, CURLOPT_POSTFIELDS, array(
'code' => $_REQUEST['code'],
'redirect_uri' => $current_url,
'client_id' => $client_id,
'client_secret' => $client_secret
));
curl_exec($ch);
curl_close($ch);
}
?>
|
|
This is the implicit flow (clientside) implementation of OAuth 2.0.
You use this when you have a Javascript application that needs to access the API.
The implementation here uses jQuery for convenience.
Step 1: Load our authorization dialog in a popup window along with a way to get back
Query String Parameters:
- redirect_uri (Required, Must reside on same domain as was used to register the application)
- client_id (Required)
Step 2: Upon authorizing that your application can access their account,
the popup will be redirected to your redirect_uri and an access token will be passed
along in the hash
Step 3: Parse the hash to gain access to the access token, and close the popup window
Connect to a live demo
|
<script type="text/javascript">
<!--
var client_id = '';
var access_token;
$(function() {
// Check to see if this page is loaded in the popup we created
if (window.opener != null && !window.opener.closed)
{
// Copy the hash (which includes the access token) received from the
// OAuth process to the main window for parsing and close the popup
opener.location.hash = window.location.hash;
window.close();
}
else
{
// Load a popup window pointing to the OAuth dialog
var url = 'http://www.daniweb.com/api/oauth/dialog?client_id='
+ client_id + '&redirect_uri=' + window.location;
// We set the location for the popup after we create it to workaround
// popup blockers that have a same-origin policy
// Most popup blockers will allow popups that are user-initiated but
// not ones that open automatically at page load; You will most likely
// want to modify this so that the dialog opens upon clicking a link
// or button or in some user-initiated way (which it doesn't)
var dialog = window.open('', 'oauth', 'height=460,width=1180');
dialog.location = url;
// Event listener for a hash change in the URI
$(window).on('hashchange', function() {
// If the URI hash changed and it's not empty ...
if (window.location.hash != '')
{
var string = window.location.hash.substr(1);
var query = string.split('&');
var param;
// Parse the URI hash to fetch the access token
for (var i = 0; i < query.length; i++)
{
param = query[i].split('=');
if (param[0] == 'access_token')
{
access_token = param[1];
break;
}
}
// We now have the access token
if (access_token !== undefined)
{
alert('Your access token is ' + access_token);
}
}
});
}
});
//-->
</script>
|
| Who Am I? |
|
GET Parameters:
|
http://www.daniweb.com/api/me?access_token={ACCESS_TOKEN}
PHP Example:
<?php
// Fetch everything about the current end-user and subsequently decode the response
// from JSON into a PHP array
$output = json_decode(file_get_contents(
'http://www.daniweb.com/api/me?&access_token='.$access_token), true);
// Print out the resulting PHP multi-dimensional associative array
echo 'Hi, ' . $output['data']['username'] . '!';
?>
Javascript (jQuery) Example:
<script type="text/javascript">
// Fetch everything about the current end-user and retrive the response as JSONP
// JSONP is a workaround for Javascript's same origin policy
$.getJSON(http://www.daniweb.com/api/me?access_token=' + access_token + '&callback=?',
function(response) { alert('Hi, ' + response.data.username + '!'); }
);
</script>
|
| Fetch Articles |
GET Parameters:
- All parameters described above
- filter (Additional, Optional)
- recommended
- viewed
- watching
- access_token (Required)
|
<?php
// This is similar to the version above, but additional filter options are available
// when passing in an access token
// Fetch C++ articles that I've recently viewed
$output = json_decode(file_get_contents(
'http://www.daniweb.com/api/forums/8/articles?
filter=viewed&access_token='.$access_token), true);
var_dump($output);
?>
|
| Fetch Private Messages |
|
GET Parameters:
|
http://www.daniweb.com/api/me/inbox?access_token={ACCESS_TOKEN}
http://www.daniweb.com/api/me/outbox?access_token={ACCESS_TOKEN}
|
| Watch an Article |
GET or POST Parameters:
- remove (Optional, Default false)
- access_token (Required)
POST Parameters:
|
http://www.daniweb.com/api/articles/watch
http://www.daniweb.com/api/articles/{:ID}/watch?access_token={ACCESS_TOKEN}
<?php
$ch = curl_init();
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
// Stop watching Article # 12345
curl_setopt($ch, CURLOPT_URL, 'http://www.daniweb.com/api/articles/watch');
curl_setopt($ch, CURLOPT_POSTFIELDS, array(
'id' => 12345,
'remove' => true,
'access_token' => $access_token
));
$output = json_decode(curl_exec($ch), true);
curl_close($ch);
?>
|
| Vote on a Post |
GET or POST Parameters:
- vote (Optional, Default 1)
- access_token (Required)
POST Parameters:
|
http://www.daniweb.com/api/posts/vote
http://www.daniweb.com/api/posts/{:ID}/vote?access_token={ACCESS_TOKEN}
<?php
$ch = curl_init();
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
// Give Post # 12345 a +1 Vote
curl_setopt($ch, CURLOPT_URL, 'http://www.daniweb.com/api/posts/vote');
curl_setopt($ch, CURLOPT_POSTFIELDS, array(
'id' => 12345,
'vote' => '1',
'access_token' => $access_token
));
$output = json_decode(curl_exec($ch), true);
curl_close($ch);
?>
|