I'm new at this, trying to hook up Box's API v2. I successfully set up a PHP client library, which I found thanks to the link in the first paragraph on developers.box.com/auth. I've read Box's walkthrough in full more than twice along with roughly 100,000 questions and replies here in regard to the matter. My problem occurs after the user redirects to Box's authorization page, enters his credentials and clicks on "Allow." The results vary according to my redirect_uri and the url of my login page where I've put my client_id and client_secret: 1) If my redirect_uri matches my https://mysite.com/login_with_box, the user redirects to that same url, obviously, which in turn sends the user back to Box's authorization page; and 2) if my redirect_uri differs from https://mysite.com/login_with_box page, then the user successfully returns to my redirect_uri, the url of which includes the 30-second code. I know that I'm close to figuring this out but don't know how to turn the code into a token in 30 seconds or less and use it to show the user's folders, files, info or whatever else. Many thanks for your consideration. Here's where I stand:
// mysite.com/client.php:
// ...
case 'Box':
$this->oauth_version = '2.0';
$this->request_token_url = '';
$this->dialog_url = 'https://api.box.com/oauth2/authorize?client_id={CLIENT_ID}&response_type=code&redirect_uri={REDIRECT_URI}&state={STATE}';
$this->append_state_to_redirect_uri = '';
$this->access_token_url = 'https://api.box.com/oauth2/token';
$this->authorization_header = true;
$this->url_parameters = false;
break;
// ...
// mysite.com/login_with_box.php:
// ...
$client->client_id = '[my_client_id]';
$client->client_secret = '[my_client_secret]';
if(($success = $client->Initialize())) {
if(($success = $client->Process())) {
if(strlen($client->access_token)) {
$success = $client->CallAPI(
'https://api.box.com/2.0/users/me',
'GET', array(), array('FailOnAccessError'=>true), $user);
}
}
$success = $client->Finalize($success);
}
// ...
It looks like you need your redirect URL to be something different from the URL that initially sends the user through the OAuth process.
For example, you could have https://mysite.com/login_with_box send the user through the OAuth process, and https://mysite.com/receive_box_oauth_response be the URL that is redirected to after the auth process and handles the OAuth response from box.
I figured it out. The problem of course was entirely my fault. Here's how I hooked up the Box API v2 with the PHP OAuth library reccommended by Box:
Create an app on developers.box.com and set the required redirect_uri to something like https://mysite.com/oauth/login_with_box.php.
Download the PHP OAuth library at www.phpclasses.org/package/7700-PHP-Authorize-and-access-APIs-using-OAuth.html
Add something like the following case to PHP OAuth library's oauth_client.php.
case 'Box':
$this->oauth_version = '2.0';
$this->request_token_url = '';
$this->dialog_url = 'https://api.box.com/oauth2/authorize?response_type=code&client_id={CLIENT_ID}&state={STATE}';
$this->append_state_to_redirect_uri = '';
$this->access_token_url = 'https://api.box.com/oauth2/token';
$this->authorization_header = true;
$this->url_parameters = false;
break;
Create something like login_with_box.php and add it to PHP OAuth library. My login_with_box.php reads as follows.
<?php
require('http.php');
require('oauth_client.php');
$client = new oauth_client_class;
$client->server = 'Box';
$client->redirect_uri = 'https://mysite.com/oauth/login_with_box.php';
$client->client_id = 'xxxxxx_BOX_API_CLIENT_ID_xxxxxx';
$client->client_secret = 'xxxxxx_BOX_API_CLIENT_SECRET_xxxxxx';
if(strlen($client->client_id) == 0 || strlen($client->client_secret) == 0)
die('You need an app to do that.');
if(($success = $client->Initialize())) {
if(($success = $client->Process())) {
if(strlen($client->access_token)) {
$success = $client->CallAPI(
'https://api.box.com/2.0/folders/0',
'GET', array('format'=>'json'), array('FailOnAccessError'=>true), $folder);
}
}
$success = $client->Finalize($success);
}
if($client->exit)
exit;
if($success) {
?>
<!doctype html>
<html>
<head>
<title>Box OAuth client results</title>
</head>
<body>
<?php echo '<h1>You successfully logged in with Box</h1>'; echo '<pre>', HtmlSpecialChars(print_r($folder, 1)), '</pre>'; ?>
</body>
</html>
<?php } else { ?>
<!doctype html>
<html>
<head>
<title>OAuth client error</title>
</head>
<body>
<h1>OAuth client error</h1>
<pre>Error: <?php echo HtmlSpecialChars($client->error); ?></pre>
</body>
</html>
<?php } ?>
I hope this helps somebody.
Related
I'm currently testing a PHP script which uses Oauth 2.0 login and some api scopes that i can retrieve logged in user information and group information.
This group information determines the redirection of that user once authorised.
This works fine but some of the api scopes are admin based scopes and only work when i log in.
Ive read about creating a service account and site wide api delegations (Which i have done) but im not sure how to implement this into my test PHP code?
index.php code
<?php
//Include Configuration File
include('config.php');
$login_button = '';
//This $_GET["code"] variable value received after user has login into their Google Account redirct to PHP script then this variable value has been received
if(isset($_GET["code"]))
{
//It will Attempt to exchange a code for an valid authentication token.
$token = $google_client->fetchAccessTokenWithAuthCode($_GET["code"]);
//This condition will check there is any error occur during geting authentication token. If there is no any error occur then it will execute if block of code/
if(!isset($token['error']))
{
//Set the access token used for requests
$google_client->setAccessToken($token['access_token']);
//Store "access_token" value in $_SESSION variable for future use.
$_SESSION['access_token'] = $token['access_token'];
//Create Object of Google Service OAuth 2 class
$google_service = new Google_Service_Oauth2($google_client);
//Get user profile data from google
$data = $google_service->userinfo->get();
//Below you can find Get profile data and store into $_SESSION variable
if(!empty($data['given_name']))
{
$_SESSION['user_first_name'] = $data['given_name'];
}
if(!empty($data['family_name']))
{
$_SESSION['user_last_name'] = $data['family_name'];
}
if(!empty($data['email']))
{
$_SESSION['user_email_address'] = $data['email'];
}
if(!empty($data['gender']))
{
$_SESSION['user_gender'] = $data['gender'];
}
if(!empty($data['picture']))
{
$_SESSION['user_image'] = $data['picture'];
}
}
}
//This is for check user has login into system by using Google account, if User not login into system then it will execute if block of code and make code for display Login link for Login using Google account.
if(!isset($_SESSION['access_token']))
{
//Create a URL to obtain user authorization
$login_button = '<img src="sign-in-with-google.png" />';
}
?>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>PHP Login using Google Account</title>
<meta content='width=device-width, initial-scale=1, maximum-scale=1' name='viewport'/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet" />
</head>
<body>
<div class="container">
<br />
<h2 align="center">PHP1 Login using Google Account</h2>
<br />
<div class="panel panel-default">
<?php
if($login_button == '')
{
echo '<div class="panel-heading">Welcome User</div><div class="panel-body">';
echo '<img src="'.$_SESSION["user_image"].'" class="img-responsive img-circle img-thumbnail" />';
echo '<h3><b>Name :</b> '.$_SESSION['user_first_name'].' '.$_SESSION['user_last_name'].'</h3>';
echo '<h3><b>Email :</b> '.$_SESSION['user_email_address'].'</h3>';
echo '<h3>Logout</h3></div>';
//echo $_SESSION['access_token'];
$gruppen = new Google_Service_Directory($google_client);
$optParams = array('userKey' => $data['id']);
$retGruppen = $gruppen->groups->listGroups($optParams);
//var_dump($gruppen->groups->listGroups($optParams));
$usergrouparray = array($gruppen->groups->listGroups($optParams));
//need to check array key ['name'] if it equals to all staff
//print_r with true converts output to string, we store the string as variable then check that variable to see if it contains All Staff
$test = print_r($usergrouparray,true);
//echo $test ; //prints all array
if (strpos($test, 'All Staff') !== false) {
echo 'true';
} else { echo 'false';}
}
else
{
echo '<div align="center">'.$login_button . '</div>';
}
?>
</div>
</div>
</body>
</html>
Config.php
<?php
//config.php
//Include Google Client Library for PHP autoload file
require __DIR__ . '/vendor/autoload.php';
//Make object of Google API Client for call Google API
$google_client = new Google_Client();
//Set the OAuth 2.0 Client ID
$google_client->setClientId('my id');
//Set the OAuth 2.0 Client Secret key
$google_client->setClientSecret('my key');
//Set the OAuth 2.0 Redirect URI
$google_client->setRedirectUri('my redirected uri here');
//
$google_client->addScope('email');
$google_client->addScope('profile');
$google_client->addScope("https://www.googleapis.com/auth/admin.directory.group.readonly");
$google_client->addScope("https://www.googleapis.com/auth/admin.directory.user");
//start session on web page
session_start();
?>
How do I go about implementing my service account so the above uses this?
Am i going about this the wrong way? I do need to tell what group they are a member of (eg. is staff or not)
Thanks for any help!
I manage to solve this by creating a new client instance and instigating my service accountjust before wanting the group information
$KEY_FILE_LOCATION = __DIR__ . '/accountkey/client-key.json';
// Create and configure a new client object.
$client = new Google_Client();
$client->setSubject('admin#yourdomainhere.etc');
$client->setApplicationName("Hello Analytics Reporting");
$client->setAuthConfig($KEY_FILE_LOCATION);
$client->addScope('email');
$client->addScope('profile');
$client->addScope("https://www.googleapis.com/auth/admin.directory.group.readonly");
$client->addScope("https://www.googleapis.com/auth/admin.directory.group");
$client->addScope("https://www.googleapis.com/auth/admin.directory.user");
$gruppen = new Google_Service_Directory($client);
$optParams = array('userKey' => $data['id']);
$retGruppen = $gruppen->groups->listGroups($optParams);
//var_dump($gruppen->groups->listGroups($optParams));
$usergrouparray = array($gruppen->groups->listGroups($optParams));
I have been having this issue for a while and I cant figure it out. My Google recaptcha code seems to work on some websites - but the exact same code when added to other websites (or even other pages within the same website) won't work.
When it doesn't work, if I do a var_dump($_POST['g-recaptcha-response']); (on the second page) I get NULL.
My initial/form code:
<script src='https://www.google.com/recaptcha/api.js'></script>
<div class="g-recaptcha" data-sitekey="xxxxx"></div>
My verification page code:
$gRecaptcha = $_POST['g-recaptcha-response'];
$response=file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret=xxxxx&response=".$gRecaptcha."&remoteip=".$_SERVER['REMOTE_ADDR']);
if($response.success==false || !$gRecaptcha){
die('xxxx');
}
There are other's that posted this question as well, but it doesn't seem any of them have a solution posted (they all just switched to a different captcha).
Any suggestions what to check next?
Your condition inside if clause is wrong. The API response is a json object, like this:
{
"success": true|false,
"challenge_ts": timestamp, // timestamp of the challenge load (ISO format yyyy-MM-dd'T'HH:mm:ssZZ)
"hostname": string, // the hostname of the site where the reCAPTCHA was solved
"error-codes": [...] // optional
}
Here's the reference:
Verifying the user's response
So first you have to decode it using json_decode() function and then check the status of user's response.
Hence your code should be like this:
if(isset($_POST['g-recaptcha-response']) && !empty($_POST['g-recaptcha-response'])){
//get verified response data
//your site secret key
$secret = 'YOUR_SECRET_KEY';
$gRecaptcha = $_POST['g-recaptcha-response'];
$gRecaptcha = "https://www.google.com/recaptcha/api/siteverify?secret=".$secret."&response=".$_POST['g-recaptcha-response'];
$response = file_get_contents($gRecaptcha);
$responseData = json_decode($response);
if($responseData->success){
// success
}else{
// failure
}
}
Use like this:
Step 1 :
put this code for validate :
<?php
$secret = "Your own code";
$sitekey = "Your own code";
if ($_SERVER['REQUEST_METHOD'] == 'POST'){
$captcha=$_POST['g-recaptcha-response'];
if(!$captcha){
header("Location: index.php?info=cap");
exit;
}
$response=json_decode(file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret=".$secret."&response=".$captcha."&remoteip=".$_SERVER['REMOTE_ADDR']), true);
if($response['success'] == false)
{
header("Location: index.php?info=cap");
exit;
}
}
?>
Step 2 : use this tag in your form :
<label>I'm not robot: </label>
<div class="g-recaptcha"></div>
Step 3 : Google API
<script src="https://www.google.com/recaptcha/api.js?onload=CaptchaCallback&render=explicit" async defer></script>
<script type="text/javascript">
var CaptchaCallback = function(){
$('.g-recaptcha').each(function(index, el) {
grecaptcha.render(el, {'sitekey' : '<?php echo $sitekey;?>'});
});
};
</script>
Verify you have added both of these in google recaptcha:
www.yourdomain.com and yourdomain.com
I want to get GMail contact list in my website using PHP.
And tutorial I referred Here
CODE:
<?php
// disable warnings
if (version_compare(phpversion(), "5.3.0", ">=") == 1)
error_reporting(E_ALL & ~E_NOTICE & ~E_DEPRECATED);
else
error_reporting(E_ALL & ~E_NOTICE);
$sClientId = '564766218700-
fgtj5fba9h15g8na4khdho1uavo0rtjq.apps.googleusercontent.com';
$sClientSecret = 'GldOKp2S2ABdp-7owp3ZO_cE';
$sCallback = 'http://localhost/GmailContact/index.php'; // callback url, don't forget
to change it to your!
$iMaxResults = 20; // max results
$sStep = 'auth'; // current step
// include GmailOath library https://code.google.com/p/rspsms/source/browse/trunk
/system/plugins/GmailContacts/GmailOath.php?r=11
include_once('GmailOath.php');
session_start();
// prepare new instances of GmailOath and GmailGetContacts
$oAuth = new GmailOath($sClientId, $sClientSecret, $argarray, false, $sCallback);
$oGetContacts = new GmailGetContacts();
if ($_GET && $_GET['oauth_token']) {
$sStep = 'fetch_contacts'; // fetch contacts step
// decode request token and secret
$sDecodedToken = $oAuth->rfc3986_decode($_GET['oauth_token']);
$sDecodedTokenSecret = $oAuth->rfc3986_decode($_SESSION['oauth_token_secret']);
// get 'oauth_verifier'
$oAuthVerifier = $oAuth->rfc3986_decode($_GET['oauth_verifier']);
// prepare access token, decode it, and obtain contact list
$oAccessToken = $oGetContacts->get_access_token($oAuth, $sDecodedToken,
$sDecodedTokenSecret, $oAuthVerifier, false, true, true);
$sAccessToken = $oAuth->rfc3986_decode($oAccessToken['oauth_token']);
$sAccessTokenSecret = $oAuth->rfc3986_decode($oAccessToken['oauth_token_secret']);
$aContacts = $oGetContacts->GetContacts($oAuth, $sAccessToken, $sAccessTokenSecret,
false, true, $iMaxResults);
// turn array with contacts into html string
$sContacts = $sContactName = '';
foreach($aContacts as $k => $aInfo) {
$sContactName = end($aInfo['title']);
$aLast = end($aContacts[$k]);
foreach($aLast as $aEmail) {
$sContacts .= '<p>' . $sContactName . '(' . $aEmail['address'] . ')</p>';
}
}
} else {
// prepare access token and set it into session
$oRequestToken = $oGetContacts->get_request_token($oAuth, false, true, true);
$_SESSION['oauth_token'] = $oRequestToken['oauth_token'];
$_SESSION['oauth_token_secret'] = $oRequestToken['oauth_token_secret'];
}
?>
<!DOCTYPE html>
<html lang="en" >
<head>
<meta charset="utf-8" />
<title>Google API - Get contact list | Script Tutorials</title>
<link href="css/main.css" rel="stylesheet" type="text/css" />
</head>
<body>
<header>
<h2>Google API - Get contact list</h2>
<a href="http://www.script-tutorials.com/google-api-get-contact-list/"
class="stuts">Back to original tutorial on <span>Script Tutorials</span></a>
</header>
<img src="oauthLogo.png" class="google" alt="google" />
<?php if ($sStep == 'auth'): ?>
<center>
<h1>Step 1. OAuth</h1>
<h2>Please click <a href="https://www.google.com/accounts
/OAuthAuthorizeToken?oauth_token=<?php echo
$oAuth->rfc3986_decode($oRequestToken['oauth_token']) ?>">this link</a> in order to
get access token to receive contacts</h2>
</center>
<?php elseif ($sStep == 'fetch_contacts'): ?>
<center>
<h1>Step 2. Results</h1>
<br />
<?= $sContacts ?>
</center>
<?php endif ?>
I am encountering with an error such as:
OAuth token parameter missing.
That’s all we know.
Questions:
1. How to get OAuth access token?
Please help me.
There are several ways to make access token request, and they vary based on the type of application you are building.
For example, a JavaScript application might request an access token using a browser redirect to Google, while an application installed on a device that has no browser uses web service requests.
Some requests require an authentication step where the user logs in with their Google account. After logging in, the user is asked whether they are willing to grant the permissions that your application is requesting. This process is called user consent.
If the user grants the permission, the Google Authorization Server sends your application an access token (or an authorization code that your application can use to obtain an access token). If the user does not grant the permission, the server returns an error.
Here is link for oauth play ground which helps to understand the concepts of Oauth.
Also, check this link for contacts API.
I'm trying to add microsoft login to an application I'm developing, but I'm repeatedly getting this error which I'm unable to understand.
The URL is :-
https://login.live.com/err.srf?lc=1033#error=invalid_request&error_description=The%20provided%20value%20for%20the%20input%20parameter%20'redirect_uri'%20is%20not%20valid.%20The%20expected%20value%20is%20'https://login.live.com/oauth20_desktop.srf'%20or%20a%20URL%20which%20matches%20the%20redirect%20URI%20registered%20for%20this%20client%20application.&state=1403724714-562028
Code
<?php
require('lib/http.php');
require('lib/oauth_client.php');
$client = new oauth_client_class;
$client->server = 'Microsoft';
//$client->redirect_uri = 'http://'.$_SERVER['HTTP_HOST'].
//dirname(strtok($_SERVER['REQUEST_URI'],'?')).'/login.php';
$client->redirect_uri='http://novostack.com/mscr/login.php';
$client->client_id = 'clietidhere'; $application_line = __LINE__;
$client->client_secret = 'secrethere';
if(strlen($client->client_id) == 0
|| strlen($client->client_secret) == 0)
die('Please go to Microsoft Live Connect Developer Center page '.
'https://manage.dev.live.com/AddApplication.aspx and create a new'.
'application, and in the line '.$application_line.
' set the client_id to Client ID and client_secret with Client secret. '.
'The callback URL must be '.$client->redirect_uri.' but make sure '.
'the domain is valid and can be resolved by a public DNS.');
/* API permissions
*/
$client->scope = 'wl.basic wl.emails wl.birthday';
if(($success = $client->Initialize()))
{
if(($success = $client->Process()))
{
if(strlen($client->authorization_error))
{
$client->error = $client->authorization_error;
$success = false;
}
elseif(strlen($client->access_token))
{
$success = $client->CallAPI(
'https://apis.live.net/v5.0/me',
'GET', array(), array('FailOnAccessError'=>true), $user);
}
}
$success = $client->Finalize($success);
}
if($client->exit)
exit;
if($success)
{
session_start();
$_SESSION['userdata']=$user;
header("location: index.php");
}
else
{
echo 'Error:'.HtmlSpecialChars($client->error);
}
?>
Here's a link to check online :- www.novostack.com/mcr/
I do have the correct settings in my developer console.
What seems to be the problem here?
All suggestions are appreciated.
Make sure that the "Root domain" under APP Settings is equal to your caller domain (www.novostack.com).
what i want to achieve is, user login in my wordpress website and also login on vanilla forum, i have installed jsconnect plugin in vanilla forum, and using the php's jsconnect library from following location jsConnectPHP
Here is my code:
require_once('functions.jsconnect.php');
$clientID = "1501569466";
$secret = "xxxxxxxxxxxxxxxxxxxxxx";
$userD = array();
if( isset($_POST['log']) ){
$data = array();
$data['user_login'] = $_POST['u_user'];
$data['user_password'] = $_POST['u_pass'];
$data['remember'] = TRUE;
$user = wp_signon($data, FALSE);
if(!is_wp_error($user)){
$userD['uniqueid'] = $user->ID;
$userD['name'] = $user->user_login;
$userD['email'] = $user->user_email;
$userD['photourl'] = '';
$secure = true;
WriteJsConnect($user, $_GET, $clientID, $secret, $secure);
$redirect = "http://localhost/vanilla/entry/jsconnect?client_id={$clientID}";
echo "<script>document.location.href='".$redirect."';</script>";
}
}
when the user login on wordpress i redirect it to jsconnect url in vanilla where i just found only a progress image, and can't figure out where is the problem..
jsconnect authentication url expects jsonp array like the following:
test({"email":"test#test.com",
"name":"testuser",
"photourl":"",
"uniqueid":1234,
"client_id":"12345678",
"signature":"XXXX"})
You authorization url you specify inside jsconnect should see this output to process further. In fact I am stuck at that point. I could see vanilla forum when loaded gets this input but no login happens.