Unable to proceed through OAuth2.0 - php

I have generated tokens and code and everything and i am able to login and authorize the user but somehow I am getting error. Two error has been spotted.
First One
(
[error] => invalid_grant
[error_description] => Authorization code doesn't exist or is invalid for the client
)
Sometimes authorization code is not generating so I am getting above error. And sometimes when I am able to generate auth_code I am getting below error
{"error":"invalid_token","error_description":"The access token provided is invalid"}
I am developer of the site abcd.com and now I have a platform where I need to develop my abcd.com for that platform. To implement login I have to use OAuth2.0 and this is the requirement of the platform. I have read a lot of documents on OAuth2.0 and build the app. I am using codeigniter though.
server.php
$dsn = 'mysql:dbname=my_oauth2_db;host=localhost';
$username = 'root';
$password = '';
// error reporting (this is a demo, after all!)
ini_set('display_errors',1);error_reporting(E_ALL);
// Autoloading (composer is preferred, but for this example let's just do this)
require_once('oauth2-server-php/src/OAuth2/Autoloader.php');
OAuth2\Autoloader::register();
// $dsn is the Data Source Name for your database, for exmaple "mysql:dbname=my_oauth2_db;host=localhost"
$storage = new OAuth2\Storage\Pdo(array('dsn' => $dsn, 'username' => $username, 'password' => $password));
// Pass a storage object or array of storage objects to the OAuth2 server class
$server = new OAuth2\Server($storage);
// Add the "Client Credentials" grant type (it is the simplest of the grant types)
$server->addGrantType(new OAuth2\GrantType\ClientCredentials($storage));
// Add the "Authorization Code" grant type (this is where the oauth magic happens)
$server->addGrantType(new OAuth2\GrantType\AuthorizationCode($storage));
$scope = new OAuth2\Scope(array(
'supported_scopes' => array('email')
));
$server->setScopeUtil($scope);
Here is my authorize.php
require_once __DIR__.'/server.php';
$request = OAuth2\Request::createFromGlobals();
$client_id = $request->query['client_id'];
$response = new OAuth2\Response();
if (!$server->validateAuthorizeRequest($request, $response)) {
$response->send();
die;
}
if (empty($_POST)) {
exit('<form method="post">
<label>Do You Authorize '.$client_id.'?</label><br />
<input class="yes_authorize" type="submit" name="authorized" value="Yes">
<input class="no_authorize" type="submit" name="authorized" value="No">
</form>');
}
$is_authorized = ($_POST['authorized'] === 'Yes');
$server->handleAuthorizeRequest($request, $response, $is_authorized);
if ($is_authorized) {
$code = substr($response->getHttpHeader('Location'), strpos($response->getHttpHeader('Location'), 'code=')+5, 40);
$client_secret = $_GET['state'];
$token_value = shell_exec("curl -u CLIENT_ID:CLIENT_SECRET https://abcd.com/api/token.php -d 'grant_type=authorization_code&code=$code'");
$token = json_decode($token_value);
$access_token = $token->access_token;
$expires_in = $token->expires_in;
$state = $_GET['state'];
$resource_result = shell_exec("curl https://abcd.com/api/resource.php -d 'access_token=$code'");
$redirect_url = $_GET['redirecturi']."?code=$access_token&state=".$_GET['state'];
exit(header("location: $redirect_url"));
}
$response->send();
resource.php
require_once __DIR__.'/server.php';
if (!$server->verifyResourceRequest(OAuth2\Request::createFromGlobals())) {
$server->getResponse()->send();
die;
}
echo json_encode(array('success' => true, 'message' => 'You accessed my APIs!'));
token.php
require_once __DIR__.'/server.php';
$server->handleTokenRequest(OAuth2\Request::createFromGlobals())->send();
If you see authorize.php, After generating access_token through token.php, If I pass that to resource.php, I am getting second error. AND I have passed auth_code as well as access_token both to my redirect url, but I am getting not able to get through.

Related

openid connect to identify server in php

I'm using https://github.com/jumbojett/OpenID-Connect-PHP this library to auth an user from identify server 4.
I'm trying to connect to identify server which has this settings
Scope : offline_access
Response type: code id_token
DefaultScheme = “Cookie”
Error I'm getting:
Sorry, there was an error : unauthorized_client
Invalid grant type for client
My code
$issuer = 'issuer';
$cid = 'clientid';
$secret = 'clientsecret';
$oidc = new Jumbojett\OpenIDConnectClient($issuer, $cid, $secret);
$oidc->addScope(array('openid', 'offline_access'));
$oidc->authenticate();
$oidc->requestUserInfo('sub');
$user = $oidc->requestUserInfo();
session_start();
$_SESSION['user'] = $user;

Twitter API in PHP using codebird

I need to incorporate twitter feature in a project of mine. Among all the libraries and wrappers, codebird seemed convenient. I tried to do the basic authentication using codes from their example, but upon uploading the files on the server, i cant get to access them at all. It shows error 500 in server and i cant test them on localhost.
the index.php file
<?php
require_once ('codebird.php');
\Codebird\Codebird::setConsumerKey('123456', '1234567'); // static, see 'Using multiple Codebird instances'
$cb = \Codebird\Codebird::getInstance();
session_start();
if (! isset($_SESSION['oauth_token'])) {
// get the request token
$reply = $cb->oauth_requestToken([
'oauth_callback' => 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']
]);
// store the token
$cb->setToken($reply->oauth_token, $reply->oauth_token_secret);
$_SESSION['oauth_token'] = $reply->oauth_token;
$_SESSION['oauth_token_secret'] = $reply->oauth_token_secret;
$_SESSION['oauth_verify'] = true;
// redirect to auth website
$auth_url = $cb->oauth_authorize();
header('Location: ' . $auth_url);
die();
} elseif (isset($_GET['oauth_verifier']) && isset($_SESSION['oauth_verify'])) {
// verify the token
$cb->setToken($_SESSION['oauth_token'], $_SESSION['oauth_token_secret']);
unset($_SESSION['oauth_verify']);
// get the access token
$reply = $cb->oauth_accessToken([
'oauth_verifier' => $_GET['oauth_verifier']
]);
// store the token (which is different from the request token!)
$_SESSION['oauth_token'] = $reply->oauth_token;
$_SESSION['oauth_token_secret'] = $reply->oauth_token_secret;
// send to same URL, without oauth GET parameters
header('Location: ' . basename(__FILE__));
die();
}
// assign access token on each page load
$cb->setToken($_SESSION['oauth_token'], $_SESSION['oauth_token_secret']);
the callback.php
<?php
require_once ('codebird.php');
\Codebird\Codebird::setConsumerKey('123456', '1234567'); // static, see 'Using multiple Codebird instances'
$cb = \Codebird\Codebird::getInstance();
if(isset($_SESSION['oauth_token'] && isset($_SESSION['oauth_token_secret']))){
$cb->setToken($_SESSION['oauth_token'], $_SESSION['oauth_token_secret']); // see above
$reply = (array) $cb->statuses_homeTimeline();
print_r($reply);
}
else {
echo 'necessary session variables couldnt be found!';
}
?>
This might be a really noob question as i have only basic knowledge in PHP, but any help would be much appriciated, please.

PHP, Codebird and Twitter why am receiving error 401 Invalid Request Token

I am trying to get access token from twitter using codebird, first getting user to authorize use of my application works perfectly using this code
require_once('lib/codebird.php');
\Codebird\Codebird::setConsumerKey("xxx", "xxxx");
$cb = \Codebird\Codebird::getInstance();
session_start();
// get the request token
$reply = $cb->oauth_requestToken(array(
'oauth_callback' => 'http://lifetanstic.co.ke/AppRegister'));
// store the token
$cb->setToken($reply->oauth_token, $reply->oauth_token_secret);
$_SESSION['oauth_token'] = $reply->oauth_token;
$_SESSION['oauth_token_secret'] = $reply->oauth_token_secret;
$_SESSION['oauth_verify'] = true;
// redirect to auth website
$auth_url = $cb->oauth_authorize();
?>
<script type="text/javascript">
window.location = "<?php echo $auth_url; ?>";
</script>
<?php
//header('Location: ' . $auth_url);
?>
This is where I am redirected here:
When then I get redirected to the window in where I am supposed to get the access token and access token secret and that also works.
Here is where using $_GET[] I get the following codes http://lifetanstic.co.ke/AppRegister?oauth_token=zzzzz&oauth_verifier=zzzz
Now in that page when I run the following code, it does not work, but produces the following error:
require_once('lib/codebird.php');
session_start();
\Codebird\Codebird::setConsumerKey("xxxx", "xxxx");
$cb = \Codebird\Codebird::getInstance();
// get the access token
$reply = $cb->oauth_accessToken(array(
'oauth_verifier' => $_GET['oauth_verifier']
));
var_dump($reply);
When I dump the reply, it has the following error in it:
object(stdClass)#1 (3) { ["message"]=> string(21) "Invalid request token" ["httpstatus"]=> int(401) ["rate"]=> NULL }
So how am I supposed to get the aouth_accessToken, with this oauth_token=zzzzz&oauth_verifier=zzzz url parameters provide and a user has authorised use of my application?
so let me answer my own question, the part of the code that did not work was this:
require_once('lib/codebird.php');
session_start();
\Codebird\Codebird::setConsumerKey("xxxx", "xxxx");
$cb = \Codebird\Codebird::getInstance();
// get the access token
$reply = $cb->oauth_accessToken(array(
'oauth_verifier' => $_GET['oauth_verifier']
));
var_dump($reply);
And i realized why, in the tutorial for codebird here https://github.com/jublonet/codebird-php there is something i thought it was not a necessary but the moment is reinstated it, it worked miracurously, this line of code
$cb->setToken($_SESSION['oauth_token'], $_SESSION['oauth_token_secret']);
So the final code will be like this:
require_once('lib/codebird.php');
session_start();
\Codebird\Codebird::setConsumerKey("xxxx", "xxxxx");
$cb = \Codebird\Codebird::getInstance();
// get the access token
$cb->setToken($_SESSION['oauth_token'], $_SESSION['oauth_token_secret']);
/*$reply = $cb->oauth_requestToken(array(
'oauth_callback' => 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']
));*/
$reply = $cb->oauth_accessToken(array(
'oauth_verifier' => $_GET['oauth_verifier']
));
//var_dump($reply);
uncomment the last line to show the results in greater details
to confirm the results, i posted to twitter successfully using this code:
$cb->setToken($reply->oauth_token, $reply->oauth_token_secret);
$params = array(
'status' => '1Auto Post on Twitter with PHP http://goo.gl/OZHaQD #php #twitter #Maina_Wycliffe'
);
$reply = $cb->statuses_update($params);
//var_dump($reply);
and here is the evidence, tweet url-> https://twitter.com/Maina_Wycliffe/status/595995951132712960
and tweets itself
Hope this will assist you
This is really weird because
$cb->setToken($_SESSION['oauth_token'], $_SESSION['oauth_token_secret']);
should not work. the first variable is not OAuth access token. You need to get this token from authorization URL - this is what was this invented for. Maybe other users may want to use your app.
Even if I have this line of code in my script I cannot tweet because I got "invalid token" error, so for me whole codebird library is a mess with no proper documentation :(

Post tweet option using php only working for me, how to make it general?

Hi all i developed an application for posting tweet using PHp with twitter api 1.1. But that option is only working for me only. If any one authenticated and try to send tweet using that. It's posting tweet on my wall.
How to make this generalized for anyone.
YOUR_CONSUMER_KEY = 'xxxxxxxxxxxxxx';
YOUR_CONSUMER_SECRET = 'xxxx';
$twitteroauth = new TwitterOAuth(YOUR_CONSUMER_KEY, YOUR_CONSUMER_SECRET);
// Requesting authentication tokens, the parameter is the URL we will be redirected to
$request_token = $twitteroauth->getRequestToken('http://xxxx/xxxx/getTwitterData.php');
//print_r($request_token);
$twitteroauth = new TwitterOAuth(YOUR_CONSUMER_KEY, YOUR_CONSUMER_SECRET, $request_token['oauth_token'], $request_token['oauth_token_secret']);
$tmessage = $_POST['message'];
$content = $twitteroauth->post('statuses/update', array('status' => $tmessage));
it's posting tweets on your wall because you're using access token and secret of the app, or you're the authenticated user. You need to log in the user you want to post for, get their access token and secret, then use consumer key, secret, user access token and user access secret to post on their behalf.
It's a bit unclear what you're trying to do, but here's a sample post action with Abraham William's library, which you're using:
require_once('twitteroauth.php');
$key = "***";
$secret = "***";
$token = "***";
$token_secret = "***";
$connection = new TwitterOAuth($key, $secret, $token, $token_secret);
$message = "whatever";
$status = $connection->post($message);
$response= $connection->http_code;
if($response !=200){
echo "ERROR";
}else{
echo "life is good";
}

Authenticate with Twitter OAuth API

I am currently trying to integreate twitter into a php web app that I am working on with OAuth.
I have an HTML page which provides a link to the twitter app authentication url which appears to be working fine and is showing the authentication screen.
Below is the code that calls the function.
if (!isset($_GET['oauth_token']))
{
//include("phpHandler/twitterLib/secret.php");
getTwitterURL($consumer_key, $consumer_secret);
}
The consumer_key and consumer_secret are included within a php file.
Below is the code that gets the twitter authorisation url.
function getTwitterUrl($consumer_key, $consumer_secret)
{
$twitterObj = new EpiTwitter($consumer_key, $consumer_secret);
$url = $twitterObj->getAuthorizationUrl();
echo '<a class="linkButtons" href="'.$url.'">Add Twitter</a>';
}
This redirect back to the page fine and then I call the authentication method to retrieve info like twitter username. Below is the function that does the authentication
function authenticate($consumer_key, $consumer_secret)
{
require ("twitterLib/EpiCurl.php");
require ("twitterLib/EpiOAuth.php");
require ("twitterLib/EpiTwitter.php");
require ("twitterLib/secret.php");*/
$twitterObj = new EpiTwitter($consumer_key, $consumer_secret);
$twitterObj->setToken($_GET['oauth_token']);
$token = $twitterObj->getAccessToken();
$twitterObj = new EpiTwitter($consumer_key, $consumer_secret);
$twitterObj->setToken($token->oauth_token, $token->oauth_token_secret);
$token = $twitterObj->getAccessToken();
$twitterObj->setToken($token->oauth_token, $token->oauth_token_secret);
$_SESSION['ot'] = $token->oauth_token;
$_SESSION['ots'] = $token->oauth_token_secret;
$twitterInfo= $twitterObj->get_accountVerify_credentials();
echo '<pre>';
print_r($twitterInfo->response);
}
The echo and print_r is to show the response return from twitter.
I am getting the following error printed out in the array
Array (
[error] => Invalid / expired Token
[request] => /account/verify_credentials.json )
How can I fix this error. I don't know why its invalid or expired, I have closed the browser and started again but get the same error appear.
Thanks for any help you can provide.
Your access token will be invalid if a user explicitly rejects your application from their settings or if a Twitter admin suspends your application. If your application is suspended there will be a note on your application page saying that it has been suspended.
Many users trust an application to read their information but not necessarily change their name or post new statuses. Updating information via the Twitter API - be it name, location or adding a new status - requires and HTTP POST. We stuck with the same restriction when implementing this. Any API method that requires an HTTP POST is considered a write method and requires read & write access.
Whatever your storage system may be, you'll need to begin storing an oauth_token and oauth_token_secret (collectively, an "access token") for each user of your application. The oauth_token_secret should be stored securely. Remember, you'll be accessing these values for every authenticated request your application makes to the Twitter API, so store them in a way that will scale to your user base. When you're using OAuth, you should no longer be storing passwords for any of your users.
require '../tmhOAuth.php';
require '../tmhUtilities.php';
$tmhOAuth = new tmhOAuth(array(
'consumer_key' => 'YOUR_CONSUMER_KEY',
'consumer_secret' => 'YOUR_CONSUMER_SECRET',
'user_token' => 'AN_ACCESS_TOKEN',
'user_secret' => 'AN_ACCESS_TOKEN_SECRET',
));
// we're using a hardcoded image path here. You can easily replace this with an uploaded image-see images.php example)
// 'image = "#{$_FILES['image']['tmp_name']};type={$_FILES['image']['type']};filename={$_FILES['image']['name']}",
$image = "./dickvandyke.jpg';
$code = $tmhOAuth->request('POST', 'https://upload.twitter.com/1/statuses/update_with_media.json',
array(
'media[]' => "#{$image}",
'status' => "Don't slip up" // Don't give up..
),
true, // use auth
true // multipart
);
if ($code == 200) {
tmhUtilities::pr(json_decode($tmhOAuth->response['response']));
} else {
tmhUtilities::pr($tmhOAuth->response['response']);
}
I've managed to find the problem. I always creating two new EpiTwitter objects in the authenticate function.
I worked on new Twitter API. It is working fine for me with following code I did.
<?php
require "vendor/autoload.php";
use Abraham\TwitterOAuth\TwitterOAuth;
$consumer_key = "XXXXXXX";
$consumer_secret = "XXXXXXX";
$connection = new TwitterOAuth($consumer_key, $consumer_secret);
$request_token= $connection->oauth('oauth/request_token', array('oauth_callback' => "http://callbackurlhere.com/callback.php"));
$url = $connection->url("oauth/authorize", array("oauth_token" => $request_token['oauth_token']));
header('Location: '. $url);
?>
callback.php code below to obtain the permanent oauthToken and save it in database for further use:
<?php
require "vendor/autoload.php";
use Abraham\TwitterOAuth\TwitterOAuth;
// session_start();
if(isset($_REQUEST['oauth_verifier'])){
$oauth_access_token = $_REQUEST['oauth_token'];
$oauth_access_token_secret = $_REQUEST['oauth_verifier'];
$consumer_key = "XXXXXXXXXXXXXXXX";
$consumer_secret = "XXXXXXXXXXXXXXX";
$connection = new TwitterOAuth($consumer_key, $consumer_secret,$oauth_access_token , $oauth_access_token_secret );
$access_token = $connection->oauth("oauth/access_token", array("oauth_verifier" => $oauth_access_token_secret));
var_dump($access_token); die("--success here--");// Obtain tokens and save it in database for further use.
}
?>

Categories