Google Apps Auth with edu.au domain - authentication

I am trying to authentify a domain for google docs scope. This is the url:
https://www.google.com/accounts/AuthSubRequest?next=http%3A%2F%2Fwww.mydomain.edu.au%2Fcomponents%2Fgoogle%2FretrieveToken.php&scope=https%3A%2F%2Fdocs.google.com%2Ffeeds%2F&session=1&secure=0&hd=default
So my domain is: www.mydomain.edu.au
But when makng the request Then i get this answer:
The page you have requested cannot be displayed. Another site was requesting access to your Google Account, but sent a malformed request. Please contact the site that you were trying to use when you received this message to inform them of the error. A detailed error message follows:
The site "http://edu.au" has not been registered.
So its identified as edu.au domain.
Is there a way around this?
Thanx
sample code for uploading document to google docs:
public static function uploadDocs($data = array())
{
if (!self::checkInput($data)) return false;
$data['url'] = Google::docsAPIUrl.'default/private/full'.self::getFolder($data['folderId']);
//"?convert=false"
$headers = Google::getAuthToken();
array_push($headers, Google::getGData());
$contentHeaders = self::getInputHeaders($data);
array_push($headers, 'Content-Length: '.$contentHeaders['length']);
array_push($headers, 'Content-Type: '.$contentHeaders['type']);
array_push($headers, 'Slug: '.Html::win2utf8($data['docTitle']));
if ($data['inputMethod'] == 'File')
{
$data['input'] = ((fread(fopen($data['input'], 'rb'), filesize($data['input']))));
}
$curl = Google::curl($data['url'], null, $data['input'], $headers);
if (Curl::checkCode($curl['code']))
{
return self::parseNewXML($curl['response']);
}
else
{
Google::$error = array('errorCode'=>$curl['code'],'errorString'=>$curl['response']);
return false;
}
}

AuthSub is deprecated. You should be using OAuth 2.0 and Drive API v2.

Related

Getting A Refresh Token From Google Using An Authorization Token Posted in Java

I have read many posts, all the Google documentation I can find and tried many iterations of the following and still can't get an access and refresh token. I do get an authorization code but can't seem to get that to trade for the access and refresh tokens.
if(authCode == null || authCode.equals("")) {
String url = "https://accounts.google.com/o/oauth2/v2/auth?"
+ "scope=https://mail.google.com/&"
+ "response_type=code&"
+ "redirect_uri=urn%3Aietf%3Awg%3Aoauth%3A2.0%3Aoob&"
+ "client_id=" + clientId +
"&access_type=offline";
URI uri = new URI(url);
logger.debug("URI for auth is: " + uri);
if (Desktop.isDesktopSupported() && Desktop.getDesktop().isSupported(Desktop.Action.BROWSE)) {
Desktop.getDesktop().browse(uri);
}
}
else {
logger.debug("Refreshing");
initRefreshToken();
}
With that, I get an access code I can cut and paste (just testing and trying to get this to work first) in my properties to get the refresh and access token.
In the initRefreshToken() method, the source is like this:
if(refreshToken.equals("")) {
logger.debug("Getting refresh token");
HttpPost post = new HttpPost("https://oauth2.googleapis.com/token");
// add request parameter, form parameters
List<NameValuePair> urlParameters = new ArrayList<>();
urlParameters.add(new BasicNameValuePair("code", authCode));
urlParameters.add(new BasicNameValuePair("client_id", clientId));
urlParameters.add(new BasicNameValuePair("client_secret", clientSecret));
urlParameters.add(new BasicNameValuePair("redirect_uri", "http://localhost:8000/"));
urlParameters.add(new BasicNameValuePair("grant_type", "authorization_code"));
try {
post.setEntity(new UrlEncodedFormEntity(urlParameters));
System.out.println("***** URL: " + urlParameters);
CloseableHttpClient httpClient = HttpClients.createDefault();
CloseableHttpResponse response = httpClient.execute(post);
System.out.println(EntityUtils.toString(response.getEntity()));
}
If this is a second or subsequent time using the code, what will be printed is:
Refersh token:
***** URL: [code=4/1AY0e-g..., client_id=370...i1h2u1s.apps.googleusercontent.com, client_secret=bAOH..., redirect_uri=https://localhost:8000/, grant_type=authorization_code]
{
"error": "invalid_grant",
"error_description": "Bad Request"
}
If the code is run and it's the first time using an authentication code, it will print:
{
"error": "redirect_uri_mismatch",
"error_description": "Bad Request"
}
I read in the Google console that exceptions are made for localhost domains so there's no need to register them. However, if there were a need to register them, it won't let you register them anyway as a domain must be a top level domain you own in order to register it. Therefore, how do I register localhost and/or exchange an authorization code for an access and refresh token in Java?
Thank you for your help.
DaImTo provided a great video about this and in that video and the blog post associated with it, the redirect_uri is listed correctly as: "urn:ietf:wg:oauth:2.0:oob". I didn't find this in the documentation but when I added it to my source code, I got access and refresh tokens as a response. Thank you very much for that help, DaImTo.

How to find user's email ID? - Google Oauth2 API PHP Client

I am implementing an Audio library manager which uses user's google drive as backend storage. I am using PHP (google-api-php-client-2.2.1) to get the user's authorization for accessing his/her google drive.
So far I am able to receive access token and refresh token using example code from google (https://developers.google.com/api-client-library/php/auth/web-app), and also tested by listing files of user's google drive.
However, I am not able to figure out programmatically which user has given authorization to my application. Just user's email address will do. I don't need any other information.
I am using the following code.
<?php
require_once 'google-api-php-client/vendor/autoload.php';
session_start();
$client = new Google_Client();
$client->setAuthConfig('client_secret.json'); //downloaded from google oauth credentials portal. It includes redirect URL
$client->setAccessType("offline"); // offline access
$client->setIncludeGrantedScopes(true); // incremental auth
$client->addScope(Google_Service_Drive::DRIVE_METADATA_READONLY);
if (! isset($_GET['code'])) {
//Get authorization and User consent from Google
$auth_url = $client->createAuthUrl();
header('Location: ' . filter_var($auth_url, FILTER_SANITIZE_URL));
} else { //Authorization completed
//Get access token
$client->authenticate($_GET['code']);
$_SESSION['access_token'] = $client->getAccessToken();
$_SESSION['refresh_token'] = $client->getRefreshToken();
echo "Access Token<br>";
var_dump ($_SESSION['access_token']); //works
echo "<br>";
echo "Refresh Token<br>";
var_dump ($_SESSION['refresh_token']); //works
echo "<br>";
$service=new Google_Service_Oauth2($client);
echo "Auth2 Service created<br>"; //Getting this print
$usr_info=$service->userinfo;
echo "User Info<br>"; //Getting this print
var_dump ($usr_info); //Getting this print, Very long JSON structure. But info is mostly pertaining to my app...no user information showing here
echo "<br>";
//$usr_info_get = $usr_info->get(); //Throwing Error
//$usr_info_get = $usr_info->get(['email']); //Throwing Error
//$usr_info_get = $usr_info->get()['email']; //Throwing Error
echo "User Info Get<br>";
//var_dump ($usr_info_get);
echo "<br>";
}
?>
The class for userInfo is like this
class Google_Service_Oauth2_Resource_Userinfo extends Google_Service_Resource
{
/**
* (userinfo.get)
*
* #param array $optParams Optional parameters.
* #return Google_Service_Oauth2_Userinfoplus
*/
public function get($optParams = array())
{
$params = array();
$params = array_merge($params, $optParams);
return $this->call('get', array($params), "Google_Service_Oauth2_Userinfoplus");
}
}
The params for get() method should be optional, but
$userInfo->get()
also given me Server Error.
I am not finding anything else from my google search on this.
I tried this (6 year old thread) but code errors out (apiHttpRequest class not found)
How to identify a Google OAuth2 user?
I tried reading about openID but seems kinda complex. Also, not sure if google-api-php-client has helper class for openID.
I would really appreciate your help. Already spent 2+ days reading google api client php code but now up against the wall.

mautic - I want to add contact in mautic via api

I want to add contact in mautic via an API. Below I have the code, but it's not adding the contact in mautic.
I have installed mautic in localhost. Studied the API form in the mautic documentation and tried to do it for at least 2 days, but I am not getting any results on it.
<?php
// Bootup the Composer autoloader
include __DIR__ . '/vendor/autoload.php';
use Mautic\Auth\ApiAuth;
session_start();
$publicKey = '';
$secretKey = '';
$callback = '';
// ApiAuth->newAuth() will accept an array of Auth settings
$settings = array(
'baseUrl' => 'http://localhost/mautic', // Base URL of the Mautic instance
'version' => 'OAuth2', // Version of the OAuth can be OAuth2 or OAuth1a. OAuth2 is the default value.
'clientKey' => '1_1w6nrty8k9og0kow48w8w4kww8wco0wcgswoow80ogkoo0gsks', // Client/Consumer key from Mautic
'clientSecret' => 'id6dow060fswcswgsgswgo4c88cw0kck4k4cc0wkg4gows08c', // Client/Consumer secret key from Mautic
'callback' => 'http://localhost/mtest/process.php' // Redirect URI/Callback URI for this script
);
/*
// If you already have the access token, et al, pass them in as well to prevent the need for reauthorization
$settings['accessToken'] = $accessToken;
$settings['accessTokenSecret'] = $accessTokenSecret; //for OAuth1.0a
$settings['accessTokenExpires'] = $accessTokenExpires; //UNIX timestamp
$settings['refreshToken'] = $refreshToken;
*/
// Initiate the auth object
$initAuth = new ApiAuth();
$auth = $initAuth->newAuth($settings);
/*
if( $auth->getAccessTokenData() != null ) {
$accessTokenData = $auth->getAccessTokenData();
$settings['accessToken'] = $accessTokenData['access_token'];
$settings['accessTokenSecret'] = 'id6dow060fswcswgsgswgo4c88cw0kck4k4cc0wkg4gows08c'; //for OAuth1.0a
$settings['accessTokenExpires'] = $accessTokenData['expires']; //UNIX timestamp
$settings['refreshToken'] = $accessTokenData['refresh_token'];
}*/
// Initiate process for obtaining an access token; this will redirect the user to the $authorizationUrl and/or
// set the access_tokens when the user is redirected back after granting authorization
// If the access token is expired, and a refresh token is set above, then a new access token will be requested
try {
if ($auth->validateAccessToken()) {
// Obtain the access token returned; call accessTokenUpdated() to catch if the token was updated via a
// refresh token
// $accessTokenData will have the following keys:
// For OAuth1.0a: access_token, access_token_secret, expires
// For OAuth2: access_token, expires, token_type, refresh_token
if ($auth->accessTokenUpdated()) {
$accessTokenData = $auth->getAccessTokenData();
echo "<pre>";
print_r($accessTokenData);
echo "</pre>";
//store access token data however you want
}
}
} catch (Exception $e) {
// Do Error handling
}
use Mautic\MauticApi;
//use Mautic\Auth\ApiAuth;
// ...
$initAuth = new ApiAuth();
$auth = $initAuth->newAuth($settings);
$apiUrl = "http://localhost/mautic/api";
$api = new MauticApi();
$contactApi = $api->newApi("contacts", $auth, $apiUrl);
$data = array(
'firstname' => 'Jim',
'lastname' => 'Contact',
'email' => 'jim#his-site.com',
'ipAddress' => $_SERVER['REMOTE_ADDR']
);
$contact = $contactApi->create($data);
echo "<br/>contact created";
Any help will be appreciated.
use Curl\Curl;
$curl = new Curl();
$un = 'mayank';
$pw = 'mayank';
$hash = base64_encode($un.':'.$pw);
$curl->setHeader('Authorization','Basic '.$hash);
$res = $curl->post(
'http://mautic.local/api/contacts/new',
[
'firstname'=>'fn',
'lastname'=>'ln',
'email'=>'t1#test.com'
]
);
var_dump($res);
This is something very simple i tried and it worked for me, please try cleaning cache and enable logging, unless you provide us some error it's hard to point you in right direction. Please check for logs in app/logs directory as well as in /var/logs/apache2 directory.
In my experience sometimes after activating the API in the settings the API only starts working after clearing the cache.
Make sure you have activated the API in the settings
Clear the cache:
cd /path/to/mautic
rm -rf app/cache/*
Then try again
If this didn't work, try to use the BasicAuth example (You have to enable this I the settings again and add a new User to set the credentials)
I suspect that the OAuth flow might be disturbed by the local settings / SSL configuration.
these steps may be useful:
make sure API is enabled(yes I know it's might be obvious but still);
check the logs;
check the response body;
try to send it as simple json via Postman
it may be one of the following problems:
Cache;
You are not sending the key:value; of the required custom field;
you are mistaken with authentication;
Good luck :)

Not able to use Magento REST APIs using OAuth

I am using Magento version 1.7.0.2 and trying to use Magento Rest APIs using OAuth Integration.
I have installed OAuth and following is the snippet of code that i have put in root directory of magento and i am running it in web browser by typing http://x.x.x.x:5009/oauth_customer.php
$callbackUrl = "http://x.x.x.x:5009/oauth_customer.php";
$temporaryCredentialsRequestUrl = "http://x.x.x.x:5009/oauth/initiate?oauth_callback=" . urlencode($callbackUrl);
$adminAuthorizationUrl = 'http://x.x.x.x:5009/oauth/authorize';
$accessTokenRequestUrl = "http://x.x.x.x:5009/oauth/token";
$apiUrl = "http://x.x.x.x:5009/api/rest";
$consumerKey = 'yourconsumerkey';
$consumerSecret = 'yourconsumersecret';
session_start();
if (!isset($_GET['oauth_token']) && isset($_SESSION['state']) && $_SESSION['state'] == 1) {
$_SESSION['state'] = 0;
}
try {
$authType = ($_SESSION['state'] == 2) ? OAUTH_AUTH_TYPE_AUTHORIZATION : OAUTH_AUTH_TYPE_URI;
$oauthClient = new OAuth($consumerKey, $consumerSecret, OAUTH_SIG_METHOD_HMACSHA1, $authType);
$oauthClient->enableDebug();
if (!isset($_GET['oauth_token']) && !$_SESSION['state']) {
$requestToken = $oauthClient->getRequestToken($temporaryCredentialsRequestUrl);
$_SESSION['secret'] = $requestToken['oauth_token_secret'];
$_SESSION['state'] = 1;
header('Location: ' . $adminAuthorizationUrl . '?oauth_token=' . $requestToken['oauth_token']);
exit;
} else if ($_SESSION['state'] == 1) {
$oauthClient->setToken($_GET['oauth_token'], $_SESSION['secret']);
$accessToken = $oauthClient->getAccessToken($accessTokenRequestUrl);
$_SESSION['state'] = 2;
$_SESSION['token'] = $accessToken['oauth_token'];
$_SESSION['secret'] = $accessToken['oauth_token_secret'];
header('Location: ' . $callbackUrl);
exit;
} else {
$oauthClient->setToken($_SESSION['token'], $_SESSION['secret']);
$resourceUrl = "$apiUrl/products";
$oauthClient->fetch($resourceUrl);
$productsList = json_decode($oauthClient->getLastResponse());
print_r($productsList);
}
} catch (OAuthException $e) {
print_r($e);
}
http://x.x.x.x:5009 is ip address followed 5009 where 5009 is port number specified.
When we run this in the browser, i always get the following error -
Invalid auth/bad request (got a 401, expected HTTP/1.1 20X or a redirect)
oauth_problem=signature_invalid&debug_sbs=Bya6oE4ujTEEFLVL6Mm04PqTA4g=
I am not able to get this work.
Note - I have generated consumer key and secret key. Not sure of how created user credentials with customer access to REST API Resources fit into the above script.
Also i want to know if we can use magento apis on any non magento site with oAuth integration programatically without the user having to grant access to application each time to generate request token.
You have to generate oauth token first. Follow this http://www.aschroder.com/2012/04/introduction-to-the-magento-rest-apis-with-oauth-in-version-1-7/ then test http://www.magentocommerce.com/api/rest/testing_rest_resources.html
If you dont want authentication you can use curl to get desired data. http://snipplr.com/view/44760/
In url pass valid magento resource url like www.yourwebsite.com/api/rest/products

gmail contextual gadget makeRequest call responds with Internal Server Error

I am building a google contextual gadget in it i use the following code to load a page:
var params = {};
url = "http://example.com:2057/tasks/create";
params[gadgets.io.RequestParameters.CONTENT_TYPE] = gadgets.io.ContentType.JSON;
params[gadgets.io.RequestParameters.AUTHORIZATION] = gadgets.io.AuthorizationType.SIGNED;
params["OAUTH_SERVICE_NAME"] = "HMAC";
params[gadgets.io.RequestParameters.METHOD] = gadgets.io.MethodType.GET;
gadgets.io.makeRequest(url, function(response)
{
if (response.data && response.data.RedirectUrl)
HandleLogin(response.data.RedirectUrl);
else if(response.text)
{
showOneSection('main');
$('#main').append(response.text);
}
else
ShowDebug(response);
}, params);
The call does not reach my server. and when i try reaching the url in a browser it returns fast.
what can be the problem? how can i trouble shoot it?
Thanks
I finally found the problem.
when making a signed request you have to first obtain a consumer key + secret key.
see http://www.google.com/support/forum/p/apps-apis/thread?tid=31db71169fb6fc77&hl=en
you can do that here: https://www.google.com/gadgets/directory/verify
without the keys google is unable to sign the request (although one would expect a proper error message).