I am able to get temporary credentials and able to get oauth token, but when I do use the returned token to fetch user details, I'm unable to fetch it thus the error.
I am using thephpleague/oauth1-client package and created a simple controller where I followed their Twitter Sample. From this, I am getting this error
League\OAuth1\Client\Credentials\CredentialsException: Received HTTP status code [401] with message "{"errors":[{"code":32,"message":"Could not authenticate you."}]}" when getting temporary credentials. in /var/www/html/PF.Site/Apps/TipsMarketplace/vendor/league/oauth1-client/src/Client/Server/Server.php:418
and here is the sample code I've created.
$server = new Twitter(array(
'identifier' => 'my-identifier',
'secret' => 'my-secret',
'callback_uri' => "http://localhost:8080/twitter/auth",
));
session_start();
if (isset($_GET['user'])) {
$tokenCredentials = unserialize($_SESSION['token_credentials']);
$user = $server->getUserDetails($tokenCredentials);
var_dump($user);
} elseif (isset($_GET['oauth_token']) && isset($_GET['oauth_verifier'])) {
$temporaryCredentials = unserialize($_SESSION['temporary_credentials']);
$tokenCredentials = $server->getTokenCredentials($temporaryCredentials, $_GET['oauth_token'], $_GET['oauth_verifier']);
unset($_SESSION['temporary_credentials']);
$_SESSION['token_credentials'] = serialize($tokenCredentials);
session_write_close();
header("Location: http://{$_SERVER['HTTP_HOST']}/twitter/auth?user=user");
exit;
} elseif (isset($_GET['denied'])) {
echo 'Hey! You denied the client access to your Twitter account!';
}
$temporaryCredentials = $server->getTemporaryCredentials();
$_SESSION['temporary_credentials'] = serialize($temporaryCredentials);
session_write_close();
$server->authorize($temporaryCredentials);
It turns out that I did not followed the 3-legged Oauth by twitter which is also indicated in the sample from the library.
In my code above, I've skipped the $server->authorize($temporaryCredentials) wherein it will show the Authorization Page/Login page of twitter.
Related
I'm still a newbie and want to ask about the task I'm working on,
in this case I'm making authentication using oauth2 to be able to access apple api,
but i have an error when signin using apple, invalid_client appears,
for invalid_client error, I've done the following way:
check the client_id used in the http request (doubts) (i've try by changing client_id)
adjust the jwt header and jwt payload to the parameters requirements (checked)
and check the JWT signature (checked)
of the three steps that I tried, I felt doubt in the script authentication or client id
please tell me where my fault is in the client_id naming or in the script section
thank you for the help, sorry for my bad english here I include the script that I use
``
$provider = new Apple([
'clientId' => 'com.example.example',
'teamId' => 'apple-team-id',
'keyFileId' => 'apple-key-file-id',
'keyFilePath' => storage_path('apple-key-file-path'),
'redirectUri' => 'http://localhost:8000/Store/Gold_Store/GoldStore-create',
]);
if(!isset($_POST['code'])){
//jika kita tidak mempunyai authorization code
$authUrl = $provider->getAuthorizationUrl();
$_SESSION['oauth2state'] = $provider->getState();
header('Location: '.$authUrl);
exit;
//check given state against previously stored one to mitigate CSRF attack
} elseif (empty($_POST['state']) || ($_POST['state'] !== $_SESSION['oauth2state'])) {
unset($_SESSION['oauth2state']);
exit('Invalid state');
}else{
//try to get access token(using the authorization code grant)
$token = $provider->getAccessToken('authorization_code', [
'code' => $_POST['code']
]);
//Optional: Now u have a token u can look up a user profile data
try {
//we got an access token, lets now get the user's detail
$user = $provider->getResourceOwner($token);
//use these details to create a new profile
printf('hello %s!', $user->getFirstName());
//refresh token
$refreshToken = $token->getRefreshToken();
$refreshTokenExpiration = $token->getRefreshTokenExpires();
} catch (Exception $e) {
//Failed to get user details
exit(':-(');
}
//use this to interact with an API on the users behalf
echo $token->getToken();
}
this is my json result
``{
"error": "invalid_client"
}
invalid_client error mean the client secret is wrong, maybe the issue in how you generate it or the details which you used.
You can check this snipped of code to test PHP apple sign in
https://gist.github.com/ameen-sarsour/e14a1d5bae5b61080dfdd5b1430c3e10
I'm trying to use djchen's Fitbit wrapper for thephpleague code to get Fitbit OAuth2 access for my website. It can be found here: https://github.com/djchen/oauth2-fitbit
This was working perfectly for a while and now suddenly, I'm getting "Forbidden" error. I can't remember changing any code on the login.php file. Any ideas as to why this would happen?
Here is my main code:
<?php namespace djchen\OAuth2\Client\Provider;
require __DIR__.'/vendor/autoload.php';
require __DIR__.'/vendor/oauth2-fitbit-master/src/Provider/Fitbit.php';
require __DIR__.'/vendor/oauth2-fitbit-master/src/Provider/FitbitUser.php';
use djchen\Oauth2\Client\Provider\Fitbit;
use djchen\Oauth2\Client\Provider\FitbitUser;
$provider = new Fitbit([
'clientId' => '****',
'clientSecret' => '****',
'redirectUri' => '****'
]);
ob_start();
ini_set('session.save_path',realpath(dirname($_SERVER['DOCUMENT_ROOT']) . '/var/php_sessions'));
session_start();
// If we don't have an authorization code then get one
if (!isset($_GET['code'])) {
echo "going down this path \n";
// Fetch the authorization URL from the provider; this returns the
// urlAuthorize option and generates and applies any necessary parameters
// (e.g. state).
$authorizationUrl = $provider->getAuthorizationUrl();
// Get the state generated for you and store it to the session.
$_SESSION['oauth2state'] = $provider->getState();
// Redirect the user to the authorization URL.
header('Location: ' . $authorizationUrl);
exit;
// Check given state against previously stored one to mitigate CSRF attack
} elseif (empty($_GET['state']) || ($_GET['state'] !== $_SESSION['oauth2state'])) {
echo $_SESSION['oauth2state'] . " is the oauth2state saved \n";
echo $_GET['state'] . " is the get_state \n";
unset($_SESSION['oauth2state']);
exit('Invalid state');
} else {
try {
// Try to get an access token using the authorization code grant.
$accessToken = $provider->getAccessToken('authorization_code', ['code' => $_GET['code']]);
echo "still going...";
// The provider provides a way to get an authenticated API request for
// the service, using the access token; it returns an object conforming
// to Psr\Http\Message\RequestInterface.
$request1 = $provider->getAuthenticatedRequest(
Fitbit::METHOD_GET,
Fitbit::BASE_FITBIT_API_URL . '/1/user/-/profile.json',
$accessToken,
['headers' => [Fitbit::HEADER_ACCEPT_LANG => 'en_US'], [Fitbit::HEADER_ACCEPT_LOCALE => 'en_US']]
// Fitbit uses the Accept-Language for setting the unit system used
// and setting Accept-Locale will return a translated response if available.
// https://dev.fitbit.com/docs/basics/#localization
);
// Make the authenticated API request and get the parsed response.
$response1 = $provider->getParsedResponse($request1);
//eventually will set variables here...
$deviceSpecificID=$response1['user']['encodedId'];
$firstName=$response1['user']['firstName'];
$lastName=$response1['user']['lastName'];
//making repeat request to get more data
$request2 = $provider->getAuthenticatedRequest(
Fitbit::METHOD_GET,
Fitbit::BASE_FITBIT_API_URL . '/1/user/-/activities/date/2017-09-23.json',
$accessToken,
['headers' => [Fitbit::HEADER_ACCEPT_LANG => 'en_US'], [Fitbit::HEADER_ACCEPT_LOCALE => 'en_US']]);
$response2=$provider->getParsedResponse($request2);
$stepsToday=$response2['summary']['steps'];
$stepGoal=$response2['goals']['steps'];
$todaysDate=date("Y-m-d");
//add variables to the session
$_SESSION['loggedin']=True;
$_SESSION['device']="fitbit";
$_SESSION['deviceSpecificID']=$deviceSpecificID;
$_SESSION['firstName'] = $firstName;
$_SESSION['lastName']=$lastName;
$_SESSION['activityArray']=$activityArray;
$_SESSION['steps']=$stepsToday;
$_SESSION['dailyGoal']=$stepGoal;
$_SESSION['todaysDate']=$todaysDate;
} catch (\League\OAuth2\Client\Provider\Exception\IdentityProviderException $e) {
// Failed to get the access token or user details.
exit($e->getMessage());
}
}
?>
I'm fairly confident that I've deduced the error is being thrown when running the line:
$accessToken = $provider->getAccessToken('authorization_code', ['code' => $_GET['code']]);
Any ideas why the error of "Forbidden" would show up? I'm not getting any php errors on my cgi_error log in my webhost's control panel.
Thank you so much in advance. I'm near pulling my hair out, and I'm not sure where to go from here.
Brett
I am using Cosenary Instagram-PHP-API (https://github.com/cosenary/Instagram-PHP-API) and have been able to successfully retrieve user media from user accounts. However, when I redirect clients to another php page (e.g. 'action.php'), I loose all the authentication and get the '400' error message saying that: The access_token provided is invalid.' I have tried passing authCode and access_token to the second page and used them for authentication but still couldn't retrieve data. How should I store and pass authentication to the second page? I am trying to delete comments and unfollow people on the second pages.
Here is the code I am using (from examples folder):
$instagram = new Instagram(array(
'apiKey' => '####',
'apiSecret' => '#####',
'apiCallback' => '...../success.php'
));
// receive OAuth code parameter
$code = $_GET['code'];
// check whether the user has granted access
if (isset($code)) {
// receive OAuth token object
$data = $instagram->getOAuthToken($code);
$username = $data->user->username;
// store user access token
$instagram->setAccessToken($data);
// now you have access to all authenticated user methods
$result = $instagram->getUserMedia();
} else {
// check whether an error occurred
if (isset($_GET['error'])) {
echo 'An error occurred: ' . $_GET['error_description'];
}
}
I am building a pretty simple web application. I'm having trouble handling the code return after a user logs in with Instagram. I'm also using another API to assist me you can find it here: https://github.com/cosenary/Instagram-PHP-API.
My homepage logs the user in you can see the php code below
<?php
require 'Instagram.php';
use MetzWeb\Instagram\Instagram;
// initialize class
$instagram = new Instagram(array(
'apiKey' => 'YOUR_APP_KEY',
'apiSecret' => 'YOUR_APP_SECRET',
'apiCallback' => 'YOUR_APP_CALLBACK' // must point to success.php
));
// create login URL
$loginUrl = $instagram->getLoginUrl();
?>
Users are successfully sent to the Instagram login page but when they authorize my app and Instagram responds with a http://your-redirect-uri?code=CODE The next page fails to render.
You can see the code for the "success" page that is supposed to be displayed below.
/**
* Instagram PHP API
*
* #link https://github.com/cosenary/Instagram-PHP-API
* #author Christian Metz
* #since 01.10.2013
*/
require_once 'Instagram.php';
use MetzWeb\Instagram\Instagram;
// initialize class
$instagram = new Instagram(array(
'apiKey' => 'YOUR_APP_KEY',
'apiSecret' => 'YOUR_APP_SECRET',
'apiCallback' => 'YOUR_APP_CALLBACK' // must point to success.php
));
// receive OAuth code parameter
$code = $_GET['code'];
// check whether the user has granted access
if (isset($code)) {
// receive OAuth token object
$data = $instagram->getOAuthToken($code);
$username = $username = $data->user->username;
// store user access token
$instagram->setAccessToken($data);
// now you have access to all authenticated user methods
$result = $instagram->getUserMedia();
} else {
// check whether an error occurred
if (isset($_GET['error'])) {
echo 'An error occurred: ' . $_GET['error_description'];
}
}
?>
If users cancel the authorization request the "success" page properly renders and displays the correct error message. So I believe my issue is in the handling of the code parameter that Instagram returns to my web app. Thanks for the help.
Check that YOUR_APP_CALLBACK redirect url is correct - it should be the same here as it is in your Instagram App. Check out their guidelines for acceptable redirect urls here: http://instagram.com/developer/authentication/
As long as $_GET['code']; is set then the plugin should take care of the rest so I would check that this is being set too.
If you haven't done this already have a look at the plugin example here.
That should get you started.
I've written a twitter api application using the following tutorial:
http://www.youtube.com/watch?v=GQaPt-gQVRI
How can I modify the script to generate a timeline stream that is specific to a user so that the application when run will show user's timeline stream and not mine (since i wrote the app and therefore it has my twitter credentials)
Thanks
the php application validates my twitter credentials using the following:
<?php
require 'tmhOAuth.php'; // Get it from: https://github.com/themattharris/tmhOAuth
// Use the data from http://dev.twitter.com/apps to fill out this info
// notice the slight name difference in the last two items)
$connection = new tmhOAuth(array(
'consumer_key' => 'my key',
'consumer_secret' => 'my secret',
'user_token' => 'my token', //access token
'user_secret' => 'my user secret' //access token secret
));
// set up parameters to pass
$parameters = array();
if ($_GET['count']) {
$parameters['count'] = strip_tags($_GET['count']);
}
if ($_GET['screen_name']) {
$parameters['screen_name'] = strip_tags($_GET['screen_name']);
}
if ($_GET['twitter_path']) { $twitter_path = $_GET['twitter_path']; } else {
$twitter_path = '1.1/statuses/user_timeline.json';
}
$http_code = $connection->request('GET', $connection->url($twitter_path), $parameters );
if ($http_code === 200) { // if everything's good
$response = strip_tags($connection->response['response']);
if ($_GET['callback']) { // if we ask for a jsonp callback function
echo $_GET['callback'],'(', $response,');';
} else {
echo $response;
}
} else {
echo "Error ID: ",$http_code, "<br>\n";
echo "Error: ",$connection->response['error'], "<br>\n";
So without having to pass a new username in the api call, how can i add a snippet to require the user to log in? and if i add that snippet for the user to log in, will the api automatically populate the authentication strings with the user's?
You can send a get request to the following url to get a users timeline.
https://api.twitter.com/1.1/statuses/user_timeline.json?screen_name=twitterapi&count=2
You can replace the parameters screen_name with the username you want to access, and you can replace count with the number of tweets you would like to get, count is optional and doesn't have to be included.
You can read more about statuses/user_timeline on the office twitter API site: https://dev.twitter.com/docs/api/1.1/get/statuses/user_timeline
If you wish to get a user to sign in then your best bet would be to use the twitteroauth library by abraham
Download and include in your project, then include the library and start a session.
require("twitteroauth/twitteroauth.php");
session_start();
Then create a new instance and authenticate with your app details. You can set a url to redirect to when the user authenticates. You also need to cache your tokens.
$twitteroauth = new TwitterOAuth('YOUR_CONSUMER_KEY', 'YOUR_CONSUMER_SECRET');
$request_token = $twitteroauth->getRequestToken('http://example.com/loggedin.php');
$_SESSION['oauth_token'] = $request_token['oauth_token'];
$_SESSION['oauth_token_secret'] = $request_token['oauth_token_secret'];
Redirect the user to twitter to authenticate
header('Location: '.$twitteroauth->getAuthorizeURL($request_token['oauth_token']));
In the file that you set twitter to redirect to you need to re-authenticate using the tokens created. Twitter will also add a parameter to your url which you use to create a access token for that user. Now when you send GET requests to twitter, it does it on behalf of the user logged in.
require("twitteroauth/twitteroauth.php");
session_start();
$twitteroauth = new TwitterOAuth('YOUR_CONSUMER_KEY', 'YOUR_CONSUMER_SECRET', $_SESSION['oauth_token'], $_SESSION['oauth_token_secret']);
$user_info = $twitteroauth->get('account/verify_credentials');
print_r($user_info);
You can get additional details from $user_info which you can cache or store in a database, which will allow you to remember users that have already authenticated. You will need to use oauth_token and oauth_secret, something like this.
$twitteroauth = new TwitterOAuth('YOUR_CONSUMER_KEY', 'YOUR_CONSUMER_SECRET', 'OAUTH_TOKEN', 'OAUTH_SECRET');