Twitter OAuth Problem - twitter

I am trying to use Twitter Oauth to login.
index.php
<?php
require ("twitteroauth/twitteroauth.php");
session_start();
// The TwitterOAuth instance
$twitteroauth = new TwitterOAuth('00000000000000000', '0000000000000000000000000000000');
// Requesting authentication tokens, the parameter is the URL we will be redirected to
$request_token = $twitteroauth->getRequestToken('http://bakasura.in/twitter/twitter_oauth.php');
// Saving them into the session
$_SESSION['oauth_token'] = $request_token['oauth_token'];
$_SESSION['oauth_token_secret'] = $request_token['oauth_token_secret'];
// If everything goes well..
if($twitteroauth->http_code==200){
// Let's generate the URL and redirect
$url = $twitteroauth->getAuthorizeURL($request_token['oauth_token']);
header('Location: '. $url);
} else {
// It's a bad idea to kill the script, but we've got to know when there's an error.
die('Something wrong happened.');
}
?>
Once the page loads it takes me to the Authorization Page When i click Allow it takes me back to the http://bakasura.in/twitter/twitter_oauth.php
<?php
require ("twitteroauth/twitteroauth.php");
if(!empty($_GET['oauth_verifier']) && !empty($_SESSION['oauth_token']) && !empty($_SESSION['oauth_token_secret'])){
// We've got everything we need
echo "Authorized";
} else {
// Something's missing, go back to square 1
//header('Location: twitter_login.php');
echo "Not Authorized";
}
?>
And it says "Not Authorized"
you can try it here http://bakasura.in/twitter/

you did not start your session in the second page. As long as you do not call session_start(), your session variables are not available
Some PHP setups have configured their php.ini to autostart your session, but when I look at your server setup, I see you are not sending out a cookie header for your php session on your second page, so I'm pretty sure that your session is not started on your second page...

Related

External login using Google for PHPBB 3.1

I currently allow users to login into my website using their PHPBB credentials. I use the method described here:
https://wiki.phpbb.com/Practical.External_login
However, I would like to upgrade to PHPBB 3.1 and also allow logins by placing a "Login with Google", "Login with Facebook" buttons on the form as an alternative.
I have the "Login with Google" working on the forum itself using the new PHPBB 3.1 feature, but I have no idea how to implement that as an external login on my website.
The biggest issue I run into is that if the login is successful using "Google", my user is redirected to the forum. However, I would like the user to be redirected to a specific page on my website.
I figured out how to do this:
Create a "Login with Google" button for example and link it to:
http://www.example.com/forum/loginoauth.php?mode=login&login=external&oauth_service=google
Here is my loginoauth.php file:
<?php
// phpBB inclusion protection
define('IN_PHPBB', true);
$phpbb_root_path = (defined('PHPBB_ROOT_PATH')) ? PHPBB_ROOT_PATH : './';
$phpEx = substr(strrchr(__FILE__, '.'), 1);
require($phpbb_root_path . 'common.' . $phpEx);
// Start session management
$user->session_begin();
$auth->acl($user->data);
if ($user->data['is_registered'])
{
redirect('http://www.example.com/profile');
}
else
{
//$autologin = $request->is_set_post('autologin');
$admin = ($admin) ? 1 : 0;
// Check if the supplied username is equal to the one stored within the database if re-authenticating
if ($admin && utf8_clean_string($username) != utf8_clean_string($user->data['username']))
{
// We log the attempt to use a different username...
add_log('admin', 'LOG_ADMIN_AUTH_FAIL');
trigger_error('NO_AUTH_ADMIN_USER_DIFFER');
}
// If authentication is successful we redirect user to previous page
// $result = $auth->login($username, $password, $autologin, $viewonline, $admin);
$result = $auth->login('','');
// The result parameter is always an array, holding the relevant information...
if ($result['status'] == LOGIN_SUCCESS)
{
redirect('http://www.example.com/profile');
}
}
?>

OAuth 2.0 access token has expired, and a refresh token is not available

I have a web based application which use Google OAuth2.0 as the login framework. It works nicely previously until yesterday. The applcation couldn't get the refresh token after the access token expired. Besides that, the "Request for permission" page had change to "Have offline access" instead of "Know who you are on Google" and "View you email"
Originally, the "Request for permission" page will request the access to "Know who you are on Google" and "View you email". After user logout and attempts second login, the "Request for permission" page will be the same too.
However, until yesterday, the "Request for permission" page changed to "Have offline access". After the access token is expired, I got the error messsage below:
PHP Fatal error: Uncaught exception 'Google_AuthException' with message 'The OAuth 2.0 access token has expired, and a refresh token is not available. Refresh tokens are not returned for responses that were auto-approved.' in /home2/xxxx/public_html/test/google-api-php-client/src/auth/Google_OAuth2.php:221
I tried $client->setAccessType('online'); . However, I still got this fatal error with me. Below is my code to get the access token :
if ($client->getAccessToken()) {
$token = $client->getAccessToken();
$authObj = json_decode($token);
$refreshToken = $authObj->refresh_token;
$user = $oauth2->userinfo->get();
$me = $plus->people->get('me');
$email = filter_var($user['email'], FILTER_SANITIZE_EMAIL); // get the USER EMAIL ADDRESS using OAuth2
$optParams = array('maxResults' => 100);
$activities = $plus->activities->listActivities('me', 'public', $optParams);
$_SESSION['access_token'] = $client->getAccessToken();
} else {
$authUrl = $client->createAuthUrl();
}
I tried to search for similar problem like me but I couldn't find one. This happened since yesterday. Before this, I never made any change on the codes.
With his comments, Fabian Parzefall helped me getting this fixed.
Here's my script :
if($client->isAccessTokenExpired()) {
$authUrl = $client->createAuthUrl();
header('Location: ' . filter_var($authUrl, FILTER_SANITIZE_URL));
}
It's actually pretty simple. Instead of asking him to click the "connect me" button (as put by the demo script provided by the GA API team), I redirect him directly.
Not sure if it's the proper/safer way, but that's the one working for me right now!
if($client->isAccessTokenExpired()) {
$client->authenticate();
$NewAccessToken = json_decode($client->getAccessToken());
$client->refreshToken($NewAccessToken->refresh_token);
}
The answer above is 'correct' but I faffed around working out where to put it(!)... so post this for any one else trying out examples that end up with tokens expiring(!).
Once your code has done whatever token stuff it needs, and your client has an access token... then check it is still valid and if not send off for reauthorisation!
// Stuff to do with getting tokens and storing in session etc...
if ($client->getAccessToken()) { // Hey! we got one!
if($client->isAccessTokenExpired()) { // Oh! its not good - go for another
$authUrl = $client->createAuthUrl();
header('Location: ' . filter_var($authUrl, FILTER_SANITIZE_URL));
exit();
}
try{
...
}

Using Twitter OAuth to authenticate API calls for trends

I am working on a website that allows the user to search for the top ten twitter trends in a city or country. At first I was only relying on Twitter's Rest API, but I was having a lot of rate limit issues (at school my rate limit disappears faster than I have a chance to use it). I know that authenticating my API calls will help me to better deal with this issue (Authenticated API calls are charged to the authenticating user’s limit while unauthenticated API calls are deducted from the calling IP address’ allotment).
I implemented #abraham's PHP library (https://github.com/abraham/twitteroauth), unfortunately my API calls aren't being authenticated. I know I have implemented #abraham's PHP library, because it prints out my user information at the end like it should. I have my twitter trend search underneath it but the API call isn't being authenticated. I am not sure how to fix this, and any help would really be appreciated!
This is what I use to get the top ten trends by country:
function showContent(){
// we're going to point to Yahoo's APIs
$BASE_URL = "https://query.yahooapis.com/v1/public/yql";
// the following code should only run if we've submitted a form
if(isset($_REQUEST['location']))
{
// set a variable named "location" to whatever we passed from the form
$location = $_REQUEST['location'];
// Form YQL query and build URI to YQL Web service in two steps:
// first, we show the query
$yql_query = "select woeid from geo.places where text='$location'";
// then we combine the $BASE_URL and query (urlencoded) together
$yql_query_url = $BASE_URL . "?q=" . urlencode($yql_query) . "&format=json";
//var_dump($location);
// show what we're calling
// echo $yql_query_url;
// Make call with cURL (curl pulls webpages - it's very common)
$session = curl_init($yql_query_url);
curl_setopt($session, CURLOPT_RETURNTRANSFER,true);
$json = curl_exec($session);
// Convert JSON to PHP object
$phpObj = json_decode($json);
// Confirm that results were returned before parsing
if(!is_null($phpObj->query->results)){
// Parse results and extract data to display
foreach($phpObj->query->results as $result){
//var_dump($result);
$woeid = $result[0]->woeid;
if (is_numeric ($location))
{
echo "<span style='color:red; padding-left: 245px;'>Please enter a city or a country</span>";
}
else if(empty($result)){
echo "No results found";
}
else {
/* echo "The woeid of $location is $woeid <br />"; */
}
}
}
$jsontrends=file_get_contents("http://api.twitter.com/1/trends/".$woeid.".json");
$phpObj2 = json_decode($jsontrends, true);
echo "<h3 style='margin-top:20px'>TRENDS: ".$phpObj2[0]['locations'][0]['name']."</h3> \r\n";
$data = $phpObj2[0]['trends'];
foreach ($data as $item) {
echo "<br />".$item['name']."\r\n";
echo "<br /> \r\n";
}
if(empty($item)){
echo "No results found";
}
}
}
I then add it to #abraham's html.inc file (along with some php to see the rate limit status) and html.inc is included in the index.php:
<h1>Top Twitter Trends</h1>
<form name='mainForm' method="get">
<input name='location' id='location' type='text'/><br/>
<button id='lookUpTrends'>Submit</button>
</form>
<?php showContent();
$ratelimit = file_get_contents("http://api.twitter.com/1/account/rate_limit_status.json");
echo $ratelimit;
?>
</div>
#abraham's index.php file has some example calls, and since my call doesn't look like this I think that is probably why it isn't being authenticated.
/* Some example calls */
//$connection->post('statuses/update', array('status' => date(DATE_RFC822)));
//$connection->post('statuses/destroy', array('id' => 5437877770));
//$connection->post('friendships/create', array('id' => 9436992));
//$connection->post('friendships/destroy', array('id' => 9436992));
Please help me find what I need to fix so that my API calls are authenticated.
update 10-21
I think in order to make an authenticated API call I need to include something like this is my code:
$connection->get('trends/place', array('id' => $woeid));
It didn't fix my problem, but maybe it is on the right track?
First off, you'll find that keeping your PHP and HTML separate will really help streamline your code and keep logical concerns separate (aggregating the data and displaying it are two different concerns)(many PHPers like MVC).
The code you have shared appears to be correct. My guess is that the issue lies in the creation of the OAuth connection, which should look something like:
<?php
/* Create TwitteroAuth object with app key/secret and token key/secret from default phase */
$connection = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET, $token,$secret);
Where CONSUMER_KEY and CONSUMER_SECRET are from your Trends Test app and $token and $secret are from the user signing in to twitter and allowing your app permission. Are all these values showing up when you create the TwitterOAuth object?
Also, be sure you update the config items in the twitteroauth.php file (specifically line 21 should be set to use the 1.1 API and line 29 should be set to 'json').

Unable to get access_token when user uses "visit web site" button from Facebook's app center

I'm trying to promote my app using app center but from the Web preview I can't visit the web site.
The link that is called is http://www.myappsite.it/?fb_source=appcenter&fb_appcenter=1&code=a_long_string
From the index.php of myappsite I use this peace of php code to get the user coming from facebook
$code = $_REQUEST["code"];
if($_REQUEST['state'] == $_SESSION['state'] && !$user && strlen($code) > 0)
{
$token_url = "https://graph.facebook.com/oauth/access_token?" .
"client_id=" . $appId . "&redirect_uri=" . urlencode("http://www.myappsite.it/") .
"&client_secret=" . $secret . "&code=" . $code;
$response = #file_get_contents($token_url);
$params = null;
parse_str($response, $params);
$graph_url = "https://graph.facebook.com/me?access_token=" . $params['access_token'];
$user = json_decode(file_get_contents($graph_url));
echo("Hello " . $user->name);
}
but $params['access_token'] is empty because the $token_url returns
{
"error": {
"message": "Error validating verification code.",
"type": "OAuthException",
"code": 100
}
}
how can I get the user logged in from tha app center preview web page?
From the Authenticated Referrals part of the docs (the App centre counts as an authenticated referral)
See A special consideration when using the Query String setting:
If you would like to use the server-side authentication flow it is
important to make sure you are passing the redirect_uri parameter
correctly when exchanging your code for an access token. You should
set your redirect_uri parameter to the click-through URL to your site
without the code parameter. In most cases the URL will look something
like:
http://www.example.com/?fb_source=search&code=CODE_HERE Once you
strip the code parameter it will become:
http://www.example.com/?fb_source=search which is the value that
should be set in redirect_uri. Please make sure that this logic is
dynamic as the query parameters appended to your click-through URL may
be subject to change.
Using your example from above, this means your redirect_uri parameter should be http://www.myappsite.it/?fb_source=appcenter&fb_appcenter=1
As Igy said:
http://www.example.com/?fb_source=search&code=CODE_HERE Once you strip the code parameter it will become:
http://www.example.com/?fb_source=search
However if you are redirecting with this url it will need to be url encoded otherwise the ? will stop the redirect parameter and add the fb_source to your request.
It should look like this when sent out:
http%3a%2f%2fwww.example.com%2f%3ffb_source%3dappcenter%26fb_appcenter%3d1
(Which is what Marco had already done which is why he is now happy that it works)
urlencode("http://www.myappsite.it/")

How to authenticate to Active Directory using iOS app

I am trying to create and iOS app that takes a users credentials and verifies it with the AD server. Is there some built in library in xCode to do that, or is it third party?
Any advice on direction to look would be greatly appreciated.
Thanks
Zach
Ok, so this was the PHP i used to make the connection to the ldap server. i am not 100% sure what is happening here, i got this code from IT Coordinator at my company. I understand all the binding and searching parts, but i dont get the the ldap_set_option part of this whole thing. Anyway after setting it up this way, you can then call the URL of the php script and pass it parameters. take a look at the PHP, and the url example with be below.
<?php
//Connection parameters
$dn = "DC=network,DC=net";
$host = "ldap://ldap.network.com";
$port = 1111
$user = $_GET['user'];
$pass = $_GET['pass'];
//$user = "user#network.net";
//$pass = "pass";
$filter = "memberof";
$keyword = "CN=USSC_ALL,CN=Users,DC=network,DC=net";
$filter = "objectclass";
$keyword = "user";
$filter = "objectcategory";
$keyword = "CN=Person,CN=Schema,CN=Configuration,DC=network,DC=net";
//The real thing with PHP
if (!empty($keyword) and !empty($dn)) {
//Connect to the AD
$adConn = ldap_connect($host, $port) or die("Could not connect!");
//Set protocol verison
ldap_set_option($adConn, LDAP_OPT_PROTOCOL_VERSION, 3) or die ("Could not set ldap protocol1");
//Set referrals... Won't work without this...
ldap_set_option($adConn, LDAP_OPT_REFERRALS, 0) or die ("Could not set ldap protocol2");
//Bind the user
$bd = ldap_bind($adConn, $user, $pass) or die ("Could not bind");
echo $bd;
//End binding
ldap_unbind($adConn);
} else {
echo "<p>No results found!</p>";
}
?>
</body>
</html>
Ok so now all you have to do is pass a username and password to the script and it will return the bind. that will give you either true or false. meaning if it bound successfully it is a correct combination of username and password.
this is how i am calling it:
http://192.268.192.1/ldap.php?user=(username here)&pass=(password here)
This is the approach that i took, and i think it is a very simple answer.
So what I have been able to find out is that i need to use PHP to do this. By creating a php file on the server, i can use built in ldap protocol to take a user name and password to the ldap server for verification. The query should then return true or false. As soon as i get this working ill post my code

Resources