OAuth H9 Google Health - oauth

I am attempting to gain three-legged Oauth access, but I can't get the first step to work. My code so far:
include("OAuth.php");
$consumer_key = "anonymous";
$consumer_secret = "anonymous";
define("URI", "http://www.google.com");
$request_token_url = URI.'/accounts/OAuthGetRequestToken?scope=https%3A%2F%2Fwww.google.com%2Fh9%2Ffeeds%2F';
$parsed = parse_url($request_token_url);
$params = array();
$oauth_consumer = new OAuthConsumer($consumer_key, $consumer_secret, NULL);
$req_req = OAuthRequest::from_consumer_and_token($oauth_consumer, NULL, "GET", $request_token_url, $params);
$sig_method = new OAuthSignatureMethod_HMAC_SHA1();
$req_req->sign_request($sig_method, $oauth_consumer, NULL);
$request = $req_req->to_url();
$session = curl_init($request);
curl_setopt($session, CURLOPT_RETURNTRANSFER, 1);
// Make the request
$response = curl_exec($session);
//Error Handling:
// there is an error while executing the request,
if (!$response) {
$response = curl_error($curl);
}
curl_close($session);
parse_str($response, $params);
$oauth_token = $params['oauth_token'];
$oauth_token_secret = $params['oauth_token_secret'];
$_SESSION['CONSUMER_KEY'] = $consumer_key;
$_SESSION['CONSUMER_SECRET'] = $consumer_secret;
$_SESSION['REQUEST_TOKEN'] = $oauth_token;
$_SESSION['REQUEST_TOKEN_SECRET'] = $oauth_token_secret;
print_r($_SESSION);
I'm using OAuth.php.
The returning array does not give me anything:
Array (
[CONSUMER_KEY] => googlecodesamples.com
[CONSUMER_SECRET] => [REQUEST_TOKEN] => [REQUEST_TOKEN_SECRET] =>
)
I found this on the Google Oauth Reference
If your application is not registered, select HMAC-SHA1 and use the following key and secret:
consumer key: "anonymous" consumer
secret: "anonymous"
I have altered the consumer_key and consumer_secret variables but the returning array remains empty.
I'm not sure what I'm doing wrong this is a basic H9 sandbox development procedure; any advice would help.

Well I have figured this one out,
When I printed the response of the curl I got a message which said:
This URL has moved here:
https://www.google.com/accounts/OAuthGetRequestToken?oauth_consumer_key=anonymous%20%20%20%20[amp;oauth_nonce]%20=%3E%20828f80d4cec64b5b6fcca5010e2aa952%20%20%20%20[amp;oauth_signature]%20=%3E%20H+WrK1WIhyFEkrHRBvjpzcVLFvs=%20%20%20%20[amp;oauth_signature_method]%20=%3E%20HMAC-SHA1%20%20%20%20[amp;oauth_timestamp]%20=%3E%201282773417%20%20%20%20[amp;oauth_version]%20=%3E%201.0%20%20%20%20[amp;scope]%20=%3E%20https://www.google.com/h9/feeds/
So once I changed the $request_token_url to this, it worked like a charm and I finally have one-leg!! two left :)

Related

I want to send the proper parameter to salesforce for authentication with JWT on Ruby

I am currently working on the project that I am going to integrate the application of my company and salesforce.
In my case, it seemed that using the JWT for authentication is better. So, I wanted to try it.
but I don't know how to generate JWT and send the proper request to salesforce on Ruby though I read docs.
What I wanted to do is that
1, create application on salesforce (done)
2, create X509 certification and set it on the application on salesforce. (done)
3, create JWT by using the secret key of X509 certification. (I think I've done it )
4, send post request with JWT parameter included in assertion params and grant_type(grant_type= urn:ietf:params:oauth:grant-type:jwt-bearer&) (I got an error)
when I send post request the errors says {"error":"invalid_grant","error_description":"invalid assertion"} so it occurs certainly because of the parameter I sent.
the code I randomly wrote is something like this.
require 'jwt'
require 'json'
require 'net/http'
require 'uri'
payload = {
"sub": "abel#example.com", ← my account on salesforce
"iss": "3MVG9pe2TCoA1PasbdvjabsodyoQFZTn0Rjsdbfjbasojdbn;oajs", ← the consumer key of the application on salesforce.
"aud": "https://test.salesforce.com"
}
public_key = Base64.urlsafe_encode64(
'USqTxNC7MMIeF9iegop3WeDvFL
075JSUECgYEA76FNJLeStdq+J6Fj2ZBYdDoeuDHv3iNA0nnIse9d6HnjbdrdvjmV
rT1CJuHh9gnNKg4tyjkbpc9IVj4/GF0mNUCgYEAynvj
qOYCzts4W7Bdumk6z8QULJ5QoYCrAgFtwra9R1HDcxTz+GPgJOVx2QBX+aQbDOaD
WV1s9WqE0/Lfi/VVUEzg1hZ8326buGRk1DRVG2Oa48==') ← this is public_key example of the certification.
rsa_private = OpenSSL::PKey::RSA.generate 2048
rsa_public = rsa_private.public_key
token = JWT.encode payload, rsa_private, 'RS256'
puts token
decoded_token = JWT.decode token, rsa_public, true, { algorithm: 'RS256' }
puts decoded_token
post = {
'grant_type': 'urn:ietf:params:oauth:grant-type:jwt-bearer',
'assertion': token
}
uri = URI.parse('https://login.salesforce.com/services/oauth2/token')
https = Net::HTTP.new(uri.host, 443)
https.use_ssl = true
response = https.post(uri.path, post.to_query)
print response.body
the PHP version of what I want to achieve is something like this.
<?php
require_once './vendor/autoload.php';
use Lcobucci\JWT\Builder;
use Lcobucci\JWT\Signer\Key;
use Lcobucci\JWT\Signer\Rsa\Sha256;
// login URL
// production: https://login.salesforce.com
// Sandbox: https://test.login.salesforce.com
define('LOGIN_URL', 'https://test.salesforce.com');
//consumer key
define('CLIENT_ID', <<consumer key of the application on salesforce>>);
//user ID
define('USER_ID', 'xxxxx#example.com');
function createjwt() {
$signer = new Sha256();
$privateKey = new Key('file://cert/server.key'); ← probably the key from certification
$time = time();
$token = (new Builder())->issuedBy(CLIENT_ID) // iss: consumer key
->permittedFor(LOGIN_URL) // aud: Salesforce login URL
->relatedTo(USER_ID) // sub: Salesforce user ID
->expiresAt($time + 3 * 60) // exp: within three mins
->getToken($signer, $privateKey);
return $token;
}
$jwt = createjwt();
echo $jwt;
function auth() {
$jwt = createjwt();
$post = array(
'grant_type' => GRANT_TYPE,
'assertion' => $jwt,
);
$curl = curl_init();
curl_setopt( $curl, CURLOPT_URL, AUTH_URL );
curl_setopt( $curl, CURLOPT_RETURNTRANSFER, 1 );
curl_setopt( $curl, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1 );
curl_setopt( $curl, CURLOPT_POSTFIELDS, $post );
$buf = curl_exec( $curl );
if ( curl_errno( $curl ) ) {
exit;
}
curl_close( $curl );
$json = json_decode( $buf );
$accinfo = array(
// URL to access
'instance_url' => $json->instance_url,
// Bearer token in order to access
'access_token' => $json->access_token,
);
return $accinfo;
}
$accinfo = auth();
EDIT
I changed a code a lot. But I still have different error that says 'initialize': Neither PUB key nor PRIV key: nested asn1 error (OpenSSL::PKey::RSAError)' around #private_key definition.
I read this and tried changing the string in private_key.pem to in one line but I didn't work ( maybe I did in a wrong way) and didn't understand the meaning of incorrect password (mentioned as the second answer) What causes "Neither PUB key nor PRIV key:: nested asn1 error" when building a public key in ruby?
def initialize
#cert_file = File.join(File.dirname(__FILE__), *%w[private_key.pem])
# #cert = Base64.urlsafe_encode64(#cert_file)
# print #cert_
# #cert_file = File.join(File.dirname(__FILE__), *%w[server.csr])
#base_url = "https://test.salesforce.com"
#auth_endpoint = "/services/oauth2/authorize"
#token_request_endpoint = "/services/oauth2/token"
#token_revoke_endpoint = "/services/oauth2/revoke"
#username = "my username"
#client_id = "pe2TCoA1~~~~" client_id
#private_key = OpenSSL::PKey::RSA.new(File.read(#cert_file))
# #private_key = OpenSSL::PKey::RSA.generate(private_key)
#rsa_public = #private_key.public_key
# #private_key = OpenSSL::PKey::RSA.new(File.read(#cert_file))
end
def claim_set
{
iss: #client_id,
sub: #username,
aud: #base_url,
exp: (Time.now + 3.minutes).to_i.to_s
}
end
def jwt_bearer_token
JWT.encode(self.claim_set.to_s, #rsa_public, 'RS256')
end
def request_auth
post = {body: {grant_type: "urn:ietf:params:oauth:grant-type:jwt-bearer", assertion: jwt_bearer_token}}
uri = URI.parse("#{#base_url}#{#token_request_endpoint}")
https = Net::HTTP.new(uri.host, 443)
https.use_ssl = true
response = https.post(uri.path, post.to_query)
print response.body
end
Salesforce.new.request_auth
end
Any advices are appreciated.
Thank you

Create webhook for trello in php

I am creating webhook for trello using trello api and mattzuba sdk, webhook is created successfully by using post method but there are two issues
On getting this webhook by using GET function, no results I found.
On changing in model (board id ive used) its not hitting to the callbackURL, i want some example code for callbackurl.
Here is my code of Example.php
$id = '558d029fd94e87c6230df746';
$callback_url = 'http://exampledomain.com/webhook.php';
$description = 'Webhook for board';
$webhook = array(
'idModel' => $id,
'callbackURL' => $callback_url,
'description' => $description,
);
$post = $trello2->post("tokens/$token/webhooks/?key=$key", array_filter($webhook));
print_r($post);
Here is the code of callbackurl page webhook.php
$json = file_get_contents('php://input');
$action = json_decode($json);
$sql = mysql_query("INSERT INTO trellowebhook (data) VALUES ('$action')",$con);
print_r($sql);

(403) Access Not Configured using Google_Service_Directory

When I run this code:
$client = new \Google_Client();
$client->setApplicationName($application_name);
$client->setClientId($client_id);
$key = file_get_contents('Google.p12');
$secret = file_get_contents('Google.json');
$cred = new \Google_Auth_AssertionCredentials(
$email_address, array(
'https://www.googleapis.com/auth/admin.directory.user',
'https://www.googleapis.com/auth/admin.directory.group'
), $key, 'notasecret', 'http://oauth.net/grant_type/jwt/1.0/bearer');
$client->setClientSecret($secret);
$client->setAssertionCredentials($cred);
if ($client->getAuth()->isAccessTokenExpired()) {
$client->getAuth()->refreshTokenWithAssertion($cred);
}
$token = $client->getAccessToken();
$client->setAccessToken($token);
$this->service = new \Google_Service_Directory($client);
$adminOptParams = array('domain' => 'mydomain.it');
$results = $this->service->users->listUsers($adminOptParams);
foreach ($results as $item) {
print_r($item);
}
I get this error:
[Google_Service_Exception]
Error calling GET https://www.googleapis.com/admin/directory/v1/users?domai
n=mydomain.it: (403) Access Not Configured. Please use Google Developers C
onsole to activate the API for your project.
Note that in Google app admin console I already done:
client_id --> approved api --> https://www.googleapis.com/auth/admin.directory.group
https://www.googleapis.com/auth/admin.directory.orgunit
https://www.googleapis.com/auth/admin.directory.user
Enable API SDK in api lists for using with App.

Retweet and destroy tweet using twitter API

I am developing an application which can send tweets to my twitter profile.
Now I need to implement retweet and delete tweet function. I implement those like following but no success. can any one help me!!
/* Delete tweet function */
$twitteroauthPost = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET);
$token = $twitteroauthPost->getRequestToken();
$connection = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET,$token['oauth_token'], $token['oauth_token_secret']);
$result = $connection->post('statuses/destroy', array('id' => $postId));
/* Retweet function */
$twitteroauthPost = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET);
$token = $twitteroauthPost->getRequestToken();
$connection = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET,$token['oauth_token'], $token['oauth_token_secret']);
$result = $connection->post('statuses/retweet', array('id' => $postId));
Then it return this
(
[request] => /1/statuses/retweet.json
[error] => Could not authenticate you.
)
This error means that the authorization header that gets sent to twitter is not correct. Since you are using a library that's been tested and is widely used I'm guessing that you have got your CONSUMER_KEY or CONSUMER_SECRET wrong. I'd just double check these.

Can't twitter status using oAuth and .net Hammock library on Windows Phone 7

I've been able setup the oAuth calls to get the users access Token following a couple blog posts:
http://sudheerkovalam.wordpress.com/2010/08/28/a-windows-phone-7-twitter-application-part-1/
and
:/byatool.com/c/connect-your-web-app-to-twitter-using-hammock-csharp/comment-page-1/#comment-9955
But I'm having problems sending a status update. I can't find any examples so I may not be setting the proper values. Here's the code which keeps returning: "Could not authenticate with OAuth."
private void Tweet()
{
var credentials = new OAuthCredentials
{
Type = OAuthType.ProtectedResource,
SignatureMethod = OAuthSignatureMethod.HmacSha1,
ParameterHandling = OAuthParameterHandling.HttpAuthorizationHeader,
ConsumerKey = TwitterSettings.ConsumerKey,
ConsumerSecret = TwitterSettings.ConsumerKeySecret,
Token = _settings.AccessToken,
TokenSecret = _settings.AccessTokenSecret,
Version = TwitterSettings.OAuthVersion,
};
var client = new RestClient
{
Authority = "http://twitter.com/oauth",
Credentials = credentials,
HasElevatedPermissions = true
};
var request = new RestRequest
{
Path = "/statuses/update.json",
Method = WebMethod.Post
};
request.AddParameter("status", TwitterTextBox.Text);
client.BeginRequest(request, new RestCallback(TwitterPostCompleted));
}
private void TwitterPostCompleted(RestRequest request, RestResponse response, object userstate)
{
Dispatcher.BeginInvoke(() => MessageBox.Show(response.Content));
}
thanks for any help,
Sam
Ah figured it out finally I was using the wrong URL need to use:
Authority = "http://api.twitter.com" and not: "http://twitter.com/oauth"
Just in case other people find this I've written a blog post on using OAth with Hammock for Twitter. Might be of use to some people!

Resources