I'm working on a project that need to call a API to get json response, but the Guzzle client auth is not working. It always redirect to the login page.
"nasa" is the database.
Here's my code:
<?php
require_once '../composer/vendor/autoload.php';
use GuzzleHttp\Client;
$client = new Client([
'base_url' => ['http://fedview.bfountain.com/{datasource}/', ['datasource' => 'nasa']]]);
$response = $client->get('service/sbapp/goalByAgency', ['auth' => ['username', 'password']]);
echo $response->getBody();
?>
I tried:
$response = $client->get('login.do?uname=username&passcode=password');
It can log in successfully.
Can anyone help me on this? (I'm using Guzzle 5) THX!
Here is the WHY - logic of what happens I will have to leave the rest of troubleshooting for you.
1) echo $response->getBody(); // prints out the login page "It always redirect to the login page"
2) $response = $client->get('service/sbapp/goalByAgency', ['auth' => ['username', 'password']]); // your $response is a login page because you ask $client->get the login page or authenticate page
3) You need to authenticate successfully for a $client
4) Then use the $client to request data via POST method (you missed this step)
see my other post: How can I use Guzzle to send a POST request in JSON?
redo your code. you are on the right track.
Related
I have started digging into Jawbone's UP API today and everything seems to go fine throughout the authentication process. The problem is that, once I get an access token back, it's always the same token, it doesn't work in any of my requests, and I can't change it with the refresh_token endpoint.
oAuth setup:
$url_params = array(
'response_type' => 'code',
'client_id' => CLIENT_ID,
'scope' => array('basic_read', 'extended_read', 'move_read'),
'redirect_uri' => 'https://my-site.com/up_auth.php',
);
These are the parameters attached to the https://jawbone.com/auth/oauth2/auth URL and I get sent to Jawbone and prompted as expected. When I accept the authorization I get kicked back to my-site.com as expected with the code in the URL. I then use the code like so
$params = array(
'client_id' => CLIENT_ID,
'client_secret' => APP_SECRET,
'grant_type' => 'authorization_code',
'code' => $code,
);
And attach those parameters to https://jawbone.com/auth/oauth2/token and finally get kicked back to my server with something similar to:
{
"access_token": "REALLY_LONG_STRING",
"token_type": "Bearer",
"expires_in": 31536000,
"refresh_token": "ANOTHER_REALLY_LONG_STRING"
}
When I use access_token to try and get a response like this
$headers = array(
'Host: my-site.rhcloud.com',
'Connection: Keep-Alive',
'Accept: application/json',
"Authorization: Bearer {$_REQUEST['access_token']}",
);
$ch = curl_init('https://jawbone.com/nudge/api/v.1.1/users/#me/moves');
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$o = curl_exec($ch);
curl_close($ch);
var_dump($o);
from the API, this is the response every time:
{
"meta": {
"code": 401,
"error_detail": "You must be logged in to perform that action",
"error_type": "authentication_error",
"message": "Unauthorized"
},
"data": {
}
}
The token never changes, even in a private browsing session, and even if I successfully refresh using the provided refresh_token and the proper API call - the call succeeds, but Jawbone gives me back the same token. If I test the same flow through the Jawbone API Console, the Bearer token in the request headers is different from the one I get here. Note that I get the same access_token when I attempt the same process with my wife's Jawbone credentials as well.
Finally figured out what was going on and heard back from Jawbone about it. It turns out that they have collisions on the backend if you use the same auth with two different clients.
For anyone else that runs into this problem, don't use the same login in two different contexts simultaneously as it will reset auths in weird ways.
In our case, we have test user accounts that are often shared between devs since it is sometimes hard to get real data unless you have the actual device. This was causing 'duplicate' logins that made Jawbone code freak out.
We got confirmation from a Jawbone dev who ran into the same problem when developing an internal app.....
Setup and information to reproduce the problem
Symfony2.2 application
LiipFunctionalTestBundle
DoctrineFixturesBundle
FOSUserBundle
For testing enviroment I use LiipFunctionalTestBundle and generate (from DoctrineFixtures) a fake SQLite database. It's configured correctly - I've been able to succesfully test my non-secured pages.
I've created a simple secured page under /secured/test with this view:
<h2 class="username">{{ app.user.username }}</h2>
I've tried with
http://symfony.com/doc/master/cookbook/testing/http_authentication.html
And I wanted to test this action with this assertion:
$client = static::createClient(array(), array(
'PHP_AUTH_USER' => 'myUserName'
'PHP_AUTH_PW' => 'password',
));
$crawler = $client->request('GET', '/secured/test');
$count = $crawler
->filter('h2.username:contains("myUserName")')
->count();
$this->assertTrue($count > 0);
The result was Failed asserting that false is true.
I've tried with
http://symfony.com/doc/master/cookbook/testing/simulating_authentication.html
And I wanted to test this action with this assertion:
$this->logIn();
$crawler = $this->client->request('GET', '/secured/test');
$count = $crawler
->filter('h2.username:contains("myUserName")')
->count();
$this->assertTrue($count > 0);
Ofcourse I changed the logIn function to diffrent username.
The result was Failed asserting that false is true.
None of these works. Whats wrong?
I've tried many other methods, but
The solution to the problem was very simple:
In my DoctrineFixtures I've created new users.. but their accounts were not enabled.
Adding this code to fixture solved the problem:
$user->setEnabled(true);
$user->setExpired(false);
$user->setLocked(false);
(becouse my test was trying to log on not enabled account, the response to "submit login form" was redirect to login page)
I would like to get content (posts) from a google+ page and post it to my website, as a feed. Is there any info how?
I read that current API does not allow that, but those topics were from the last year.
Thanks.
You can perform activities.list, without having to authenticate, by passing your "simple" key from the API console for a project created that has the Google+ service turned on. Access to the API calls is restricted to the authorized origins you set up in your project.
After you create the project, in the section "Simple API Access" there is an API key. Build your client with this key, your client id, and client secret:
<?
$client = new Google_Client();
$client->setDeveloperKey("YOUR_API_KEY");
$plus = new Google_PlusService($client);
$activities = $plus->activities->listActivities("+GooglePlusDevelopers", "public");
?>
<html><body><pre><? echo print_r($activities);?></pre></body></html>
A final note, make sure you use the latest Google+ PHP client.
After some time I found it.
http://code.google.com/p/google-plus-php-starter/
and this
https://developers.google.com/+/api/latest/activities/list
The only problem is that you need to log into your google app to do this. Any sugggestions would be apprecited.
Updating the correct answer, the class name has changed to Google_Service_Plus
<?php
set_include_path(get_include_path() . PATH_SEPARATOR . __DIR__ .'/vendor/google/apiclient/src');
require_once __DIR__.'/vendor/autoload.php';
$client = new Google_Client();
$client->setDeveloperKey("YOUR_API_KEY");
$plus = new Google_Service_Plus($client);
$activities = $plus->activities->listActivities("+GooglePlusDevelopers", "public");
?>
$items = $activities->getItems();
foreach($items as $item) {
$object = $item->getObject();
?>
<div class="gpost">
<p><?php echo $object->getContent(); ?></p>
Read more
</div>
<?php } ?>
i'm using the examples provided in the "google-api-php-client"-Library (http://code.google.com/p/google-api-php-client/) to implement user login and authorization on my website with google services.
I didn't make any changes to the examples, except adding my Client-ID, etc..
The authorization itself works fine: Users can login and i can fetch the provided informations.
However, when leaving the page, the whole authorization procedure is called again; users are not remembered and need to grant permissions again, which is some kind of annoying and not typical for google-logins as i know them.
For example: On stackoverflow, i'm logged in with my google account.
Whenever i revisit this site, i'm logged in automaticly, or (if logged out) just have to log in again - i do not have to confirm the general rights again.
Using the examples on my site however, forces the user to allow access whenever the site is visited again.
Did i make any mistakes, when using the examples?
What do i have to do, to avoid the permission request over and over again?
Thanks in advance for any kind of help!
Use this code for first time to retrieve access_code and save it to database:
<?php
require 'google-api-php-client/src/Google_Client.php';
require 'google-api-php-client/src/contrib/Google_DriveService.php';
require 'google-api-php-client/src/contrib/Google_Oauth2Service.php';
session_start();
$client = new Google_Client();
$client->setClientId(CLIENT_ID);
$client->setClientSecret(CLIENT_SECRET);
$client->setRedirectUri(REDIRECT_URI);
$client->setScopes(array(
'https://www.googleapis.com/auth/drive',
'https://www.googleapis.com/auth/userinfo.email',
'https://www.googleapis.com/auth/userinfo.profile'));
$client->setUseObjects(true);
$service = new Google_DriveService($client);
$client->authenticate();
$_SESSION['token'] = $client->getAccessToken();
const ACCESS_TOKEN=$_SESSION['token'];
//code here to save in database
?>
Once ACCESS_TOKEN is saved in database change code to:
<?php
require 'google-api-php-client/src/Google_Client.php';
require 'google-api-php-client/src/contrib/Google_DriveService.php';
require 'google-api-php-client/src/contrib/Google_Oauth2Service.php';
session_start();
$client = new Google_Client();
$client->setClientId(CLIENT_ID);
$client->setClientSecret(CLIENT_SECRET);
$client->setRedirectUri(REDIRECT_URI);
$client->setScopes(array(
'https://www.googleapis.com/auth/drive',
'https://www.googleapis.com/auth/userinfo.email',
'https://www.googleapis.com/auth/userinfo.profile'));
$client->setUseObjects(true);
$service = new Google_DriveService($client);
//ACCESS_TOKEN is already saved in database, is being saved on first time login.
$_SESSION['access_token'] = ACCESS_TOKEN;
if (isset($_SESSION['access_token'])) {
$client->setAccessToken($_SESSION['access_token']);
}
if ($client->getAccessToken())
{
$userinfo = $service->about->get();
echo '<script>console.log('.json_encode($userinfo).');</script>';
$userinfoService = new Google_OAuth2Service($client);
$user = $userinfoService->userinfo->get();
echo '<script>console.log('.json_encode($user).');</script>';
}
?>
That works fine for me.
Based on the kaushal's answer:
<?php
require_once 'globals.php';
require_once 'google-api-php-client/src/Google_Client.php';
require_once 'google-api-php-client/src/contrib/Google_DriveService.php';
$client = new Google_Client();
// Get your credentials from the APIs Console
$client->setClientId('YOUR_ID');
$client->setClientSecret('YOUR_SECRET');
$client->setRedirectUri('REDIRECT_URI');
$client->setScopes(array('https://www.googleapis.com/auth/drive'));
$service = new Google_DriveService($client);
$client->setUseObjects(true);
//if no token in the session
if ($_SESSION['google_token'] == '') {
//get stored token from DB
$sToken = $oDb->getOne("SELECT `google_token` FROM `users` WHERE `u_id` = " . (int)$_SESSION['user_id']);
//if no stored token in DB
if ($sToken == '') {
//autentificate user
$client->authenticate();
//get new token
$token = $client->getAccessToken();
//set token in session
$_SESSION['google_token'] = $token;
// set token in DB
$oDb->Query("UPDATE `users` SET `google_token`='$token' WHERE `u_id` = " . (int)$_SESSION['user_id']);
} else {
$_SESSION['google_token'] = $sToken;
}
}
$client->setAccessToken($_SESSION['google_token']);
//do what you wanna do with clients drive here
?>
The Google Drive SDK documentation includes a complete PHP sample application that you can use as a reference to get started:
https://developers.google.com/drive/examples/php
Basically, once the user is logged in and you retrieve access token and refresh token, you store those credentials in a database and reuse them instead of asking the user to authenticate every time.
I'm trying to find information on securing a HTTP REST API in a Symfony project, but all I can find is information about using sfGuardPlugin. From what I can see, this plugin isn't very useful for web services. It tries to have user profile models (which aren't always that simple) and have "sign in" and "sign out" pages, which obviously are pointless for a stateless REST API. It does a lot more than I'll ever have need for and I what to keep it simple.
I want to know where to implement my own authorisation method (loosely based on Amazon S3's approach). I know how I want the authorisation method to actually work, I just don't know where I can put code in my Symfony app so that it runs before every request is processed, and lets approved requests continue but unsuccessful requests return a 403.
Any ideas? I can't imagine this is hard, I just don't know where to start looking.
There is a plugin for RESTful authentication -> http://www.symfony-project.org/plugins/sfRestfulAuthenticationPlugin
Not used it though ....
How where you planning to authenticate users ?
The jobeet tutorial uses tokens ... http://www.symfony-project.org/jobeet/1_4/Doctrine/en/15
I ended up finding what I was looking for by digging into the code for sfHttpAuthPlugin. What I was looking for was a "Filter". Some details and an example is described in the Askeet sample project.
Stick a HTTP basicAuth script in your <appname>_dev.php (Symfony 1.4 =<) between the project configuration "require" and the configuration instance creation.
Test it on your dev. If it works, put the code in your index.php (the live equivalent of <appname>_dev.php) and push it live.
Quick and dirty but it works. You may want to protect that username/password in the script though.
e.g.
$realm = 'Restricted area';
//user => password
$users = array('username' => 'password');
if (empty($_SERVER['PHP_AUTH_DIGEST'])) {
header('HTTP/1.1 401 Unauthorized');
header('WWW-Authenticate: Digest realm="'.$realm.
'",qop="auth",nonce="'.uniqid().'",opaque="'.md5($realm).'"');
die('Text to send if user hits Cancel button');
}
// || !isset($users[$data['username']]
// analyze the PHP_AUTH_DIGEST variable
if (!($data = http_digest_parse($_SERVER['PHP_AUTH_DIGEST'])) || !isset($users[$data['username']])) {
header('HTTP/1.1 401 Unauthorized');
header('WWW-Authenticate: Digest realm="'.$realm.
'",qop="auth",nonce="'.uniqid().'",opaque="'.md5($realm).'"');
die('Wrong Credentials!');
}
// generate the valid response
$A1 = md5($data['username'] . ':' . $realm . ':' . $users[$data['username']]);
$A2 = md5($_SERVER['REQUEST_METHOD'].':'.$data['uri']);
$valid_response = md5($A1.':'.$data['nonce'].':'.$data['nc'].':'.$data['cnonce'].':'.$data['qop'].':'.$A2);
if ($data['response'] != $valid_response) {
header('HTTP/1.1 401 Unauthorized');
header('WWW-Authenticate: Digest realm="'.$realm.
'",qop="auth",nonce="'.uniqid().'",opaque="'.md5($realm).'"');
die('Wrong Credentials!');
}
// function to parse the http auth header
function http_digest_parse($txt)
{
// protect against missing data
$needed_parts = array('nonce'=>1, 'nc'=>1, 'cnonce'=>1, 'qop'=>1, 'username'=>1, 'uri'=>1, 'response'=>1);
$data = array();
$keys = implode('|', array_keys($needed_parts));
preg_match_all('#(' . $keys . ')=(?:([\'"])([^\2]+?)\2|([^\s,]+))#', $txt, $matches, PREG_SET_ORDER);
foreach ($matches as $m) {
$data[$m[1]] = $m[3] ? $m[3] : $m[4];
unset($needed_parts[$m[1]]);
}
return $needed_parts ? false : $data;
}
// ****************************************************************************
// ok, valid username & password.. continue...