Wednesday, July 23, 2014

Php & MySql oAuth Server & Client Example

Server side common.php (Need to include in all server side scripts)


<?php
require_once 'oauthLibrary/OAuthServer.php';
session_start();
 
// Add a header indicating this is an OAuth server
header('X-XRDS-Location: http://' . $_SERVER['SERVER_NAME'] . '/services.xrds.php');
 
// Connect to database
$db = new PDO('mysql:host=localhost;dbname=oauthdb', 'root', '');
 
// Create a new instance of OAuthStore and OAuthServer
$store = OAuthStore::instance('PDO', array('conn' => $db));
$server = new OAuthServer();
OAuthRequestLogger::enableLogging($store);
?>

Client side common.php (Need to include in all client side scripts)


<?php
session_start();

define("PATH_URL_CLIENT", "/oauth/client");
define("PATH_URL_SERVER", "/oauth/server");

define("REQUEST_TOKEN", "REQUEST_TOKENsdsdfw324ft3f3f34r34");
define("ACCESS_TOKEN", "ACCESS_TOKENkdfj33jdl23");
define("OAUTH_TOKEN", "OAUTH_TOKENdfs34fre45u67jyu");
define("OAUTH_VERIFIER", "OAUTH_VERIFIERslsjlf32j3jlfj");


require './lib/OAuthClient.php';
$client = new OAuthClient('8179e89ff6558cce5628e60643a7124c053cfc204', 'f46dfa522890df25e71ccd9db463a708');

function getServerUrl() {
    return "http://".$_SERVER["HTTP_HOST"].PATH_URL_SERVER;
}

function getClientUrl() {
    return "http://".$_SERVER["HTTP_HOST"].PATH_URL_CLIENT;
}

function toSession($key, $value) {
    $_SESSION[$key] = is_null($value) ? $value : serialize($value);
}

function fromSession($key) {
    if(isset($_SESSION[$key]) && !is_null($_SESSION[$key])) {
        return unserialize($_SESSION[$key]);
    }
    return null;
}
?>

1. Browse http://localhost/oauth/server/registration.html and fill up all fields.


2. You will be view the following information which will need to communication to server.


3. Browse the following url to get the token url, copy the url and browse

4. If you logged in success in server url, you will redirect to your callback url you specified when registration with token & verifier.


5. You are now ready to request data from server.


Download full code example.

No comments:

Post a Comment