Twitter OAuth Pin based authorization 'oob' in Google Apps Script - javascript

I am trying to use Twitter Pin-based authorization in my Google Apps Script to eventually send tweets on behalf of other uses.
I freely admit that I don't relay know what I'm doing but I have read a lot of info on the internet and feel I have tried everything.
My current Google Apps Script JavaScript code:
var method = 'post';
var url = 'https://api.twitter.com/oauth/request_token';
var consumerKey = '[my consumer key]';
var ticks = '1422745454';
var nonce = '6826266';
var options = {
'method': method,
'oauth_callback': 'oob',
'oauth_consumer_key': consumerKey,
'oauth_nonce': nonce,
'oauth_signature': 'cIFeptE5HjHp7xrp%2BZt9xFhHox4%3D',
'oauth_signature_method': 'HMAC-SHA1',
'oauth_timestamp': ticks,
'oauth_version': '1.0'
};
var response = UrlFetchApp.fetch(url, options);
For testing I set the ticks just before each test run to the value here
The nonce is a random number between 111111 and 9999999 which is regenerated before each test run.
The oauth signature I have been generating with some c# code lifted from the linq2twitter project
I suspect the problem is the signature. I have read the twitter documentation on creating a signature and I think the C# code is doing it correctly but I am not sure.
The problem is that whatever I try I always get this error:
"Request failed for https://api.twitter.com/oauth/request_token returned code 401. Truncated server response: Failed to validate oauth signature and token (use muteHttpExceptions option to examine full response)"
I have been trying to find an example of Twitter Pin-based authorization in a Google Apps Script but have so far not found anything.
My attempts to translate examples in C#, PHP, etc. have also failed.
Please help.

Apps Script provides an Oauth API that works with UrlFetchApp, they even use twitter in their examples. Work with those if at all possible, troubleshooting signature generation is a real hassle.
https://developers.google.com/apps-script/reference/url-fetch/o-auth-config
https://developers.google.com/apps-script/articles/twitter_tutorial
If you absolutely must do it from scratch, the best approach is to get requests working with an existing library (like the c# one you mention), then work on getting your apps script to generate the exact same request.
I get the sense that is what you are doing now, so it may just be a matter of base64 encoding your Signature in the outgoing request:
https://developers.google.com/apps-script/reference/utilities/utilities#base64Encode(String)
Ultimately, it's very difficult to do the whole Oauth process manually in Apps Script. When I tried something like this from scratch about a year ago I ultimately gave up and used a Python application deployed to Google App Engine instead. I submit requests from Apps Script to the App Engine application, and the App Engine application handles Oauth and relays my requests on to the external service, before returning requests to my Apps Script. This approach comes with complications of it's own.

Related

Why my geoip query doesn't work in my production server?

I'm getting a hard time making Maxmind's geolite2 geolocation work on client side.
First I found this page: https://dev.maxmind.com/geoip/geolocate-an-ip/web-services?lang=en
And tried to use the urls in the curl command with authentication with my generated license key:
let geoData = axios.get('https:///geolite.info/geoip/v2.1/country/me?pretty', {
auth: {
username: <myuser>,
password: <mylicensekey>
}
});
this works in node but in client-side I get a CORS error.
then I found this other page: https://dev.maxmind.com/geoip/geolocate-an-ip/client-side-javascript?lang=en
It worked but I didn't want to use a non-npm packaged lib, so I inspected the lib's source-code and saw it call a different url from above:
https://geoip-js.com/geoip/v2.1/country/me?
trying this new url I saw it worked only WITHOUT authentication. I didn't understand why but anyway... it worked. Until I send the code to production at least.
With localhost it worked ok, but in production I get an error saying I have to register my domain.
The link provides in "register your domain" in this page: https://dev.maxmind.com/geoip/geolocate-an-ip/client-side-javascript?lang=en
leads to https://www.maxmind.com/en/accounts/790937/geoip/javascript/domains which asks me to enter the paid service registration page: https://www.maxmind.com/en/accounts/790937/geoip/javascript/domains
Is that it ? Client-side geolocation is only available as a paid service ?
So I want to know:
If there is a way to register domains for the free service, where do I register my domain?
If I can use https://geolite.info/geoip/v2.1/country/me?pretty url with id and license key in client-side, how to I get rid of the CORS message ?
I want to get the data without sending the user's IP, like when we access https://geolite.info/geoip/v2.1/country/me?pretty with id and license key.
Currently I want to use MaxMind's free data.

ZAP scripts behave inconsistnently

I am trying to set up authentication and http sender script for Open API scanning project.
At some point in time I have reached a state where authentication script for oauth2 is working correctly (produces valid token obtained from remote endpoint) and http_sender appends authorization header for requests. It turned out later that I mistyped required header so I changed it's name, saved the script and rerun the script (via scan). Turned out now both headers are appended to outgoing http requests: mistyped version and correct one. Behavior does not change after restarting ZAP and reloading session, but mistyped header disappears when I create a new session, I can't find where can I clean it up and it does not look right to recreate session when one minor change is needed in the script.
The second issue that I have is that authentication script just stopped working without any modifications to it. I switch between environments occasionally but code remains the same. I even moved hardcoded values from context to script and it still does not work. I have set up a parallel script in python to fetch the token and it works (all parameters being the same), but in ZAP I get authentication failure (recreating session does not help). I don't own the oauth endpoint so it's not possible for me to take a look at it directly, but I suspect that both problems have something in common. Looks like some data is residing in the shadows and affects how the scripts are run.
First version of sender script:
function sendingRequest(msg, initiator, helper) {
var loginToken = org.zaproxy.zap.extension.script.ScriptVars.getGlobalVar("logintoken");
msg.getRequestHeader().setHeader("Autentication", "Bearer " + loginToken);
}
Second version of sender script:
function sendingRequest(msg, initiator, helper) {
var loginToken = org.zaproxy.zap.extension.script.ScriptVars.getGlobalVar("logintoken");
msg.getRequestHeader().setHeader("Authorization", "Bearer " + loginToken);
}```
Authentication function is just tuned version of the zap template to send oauth2 parameters in the body of the POST request and actually worked for some time. It would really help to have some troubleshooting capabilities during scripting.
Re the first issue, it all depends on how the script is being used. The ZAP session is a record of all of the requests and responses. For some of the old responses you used the wrong header. That hapenned, you cant take it back. If you reuse those requests then ZAP will send the wrong header unless you remove it. If you create new requests that are not based on historic ones then the header should not be present.
Re the second issue, authentication is hard and can fail for what seems like minor differences :( One good option would be to proxy your python script through ZAP. Hopefully it will still work, and then you can compare the working request with the failing one.

getJSON function get data from url on localhost only

I use below function to get the Continent Code from the api which works fine on localhost but fail in live environment which is website
$.getJSON('//www.geoplugin.net/json.gp?jsoncallback=?', function (data) {
// console.log(JSON.stringify(data, null, 2));
console.log(JSON.stringify(data.geoplugin_continentCode));
});
Warning which i see in Console is
Loading failed for the with source
“https://www.geoplugin.net/json.gp?jsoncallback=jQuery16407901144106031991_1537089290623&_=1537089292750”.
I am not sure why it fails on website https://www.example.com
could SSL version some problem as i am not sure as i tried it on fiddle & it works fine http://jsfiddle.net/om8ahkp3/
UPDATE
Since problem was due to crossdomain issue which as this api used a different url for ssl version. i was not able to use this ssl version as it was not free.
So ended up using another api which had free option also limited to 50k request on monthly basis.
$.ajax({
url: 'https://api.ipgeolocation.io/ipgeo?fields=is_eu& excludes=ip&apiKey=YOURKEY',
dataType: 'json',
success: function (json) {
console.log("json.is_eu " + json.is_eu);
}
});
What is the whole problem?
You want to access to a third site (crossDomain). So, That site decides that you can access to it, or not. When a site provides a service (similar geo service that you have used it), it determines which part of it's services are free.
In your case, if your source site's protocol is http (like as localhost) and dest site (service provider site) is http too, you can access to this geo service with your above code (because this third site allows this now). But if you want to access to this service from a https site (I think you are trying this now) the geoPlugin don't allow you easily or free!
In this cases, the destination sites, provide another urls and define user levels (to getting money for special services.).
In act, if your dest site was for yourself too(which it is not in this case), you could add needed access to specific referer sites, but now...
I look at its site to be sure. You must use this url in this case:
https://ssl.geoplugin.net/json.gp?k=yourAPICode
But this is not all of things! What is k in above url? This site writes:
"For SSL access, an API Key is required to offset certificate prices and costs €12 per year."
I don't know, but if you need it, you should search for free plugins (if exists) or buy it.

facebook graph api node.js invalid appsecret_proof

this is my first post so please go easy on me!
I am a beginning developer working with javascript and node.js. I am trying to make a basic request from a node js file to facebook's graph API. I have signed up for their developer service using my facebook account, and I have installed the node package for FB found here (https://www.npmjs.com/package/fb). It looks official enough.
Everything seems to be working, except I am getting a response to my GET request with a message saying my appsecret_proof is invalid.
Here is the code I am using (be advised the sensitive info is just keyboard mashing).
let https = require("https");
var FB = require('fb');
FB.options({
version: 'v2.11',
appId: 484592542348233,
appSecret: '389fa3ha3fukzf83a3r8a3f3aa3a3'
});
FB.setAccessToken('f8af89a3f98a3f89a3f87af8afnafmdasfasedfaskjefzev8zv9z390fz39fznabacbkcbalanaa3fla398fa3lfa3flka3flina3fk3anflka3fnalifn3laifnka3fnaelfafi3eifafnaifla3nfia3nfa3ifla');
console.log(FB.options());
FB.api('/me',
'GET',
{
"fields": "id,name"
},
function (res) {
if(!res || res.error) {
console.log(!res ? 'error occurred' : res.error);
return;
}
console.log(res);
console.log(res.id);
console.log(res.name);
}
);
The error I am getting reads:
{ message: 'Invalid appsecret_proof provided in the API argument',
type: 'GraphMethodException',
code: 100,
fbtrace_id: 'H3pDC0OPZdK' }
I have reset my appSecret and accessToken on the developer page and tried them immediately after resetting them. I get the same error, so I don't think that stale credentials are the issue. My
console.log(FB.options())
returns an appropriate looking object that also contains a long hash for appSecretProof as expected. I have also tried this code with a number of version numbers in the options (v2.4, v2.5, v2.11, and without any version key). Facebook's documentation on this strikes me as somewhat unclear. I think I should be using v2.5 of the SDK (which the node package is meant to mimic) and making requests to v2.11 of the graph API, but ??? In any case, that wouldn't seem to explain the issue I'm having. I get a perfectly good response that says my appSecretProof is invalid when I don't specify any version number at all.
The node package for fb should be generating this appSecretProof for me, and it looks like it is doing that. My other info and syntax all seem correct according to the package documentation. What am I missing here? Thank you all so much in advance.
looks like you have required the appsecret_proof for 2 factor authorization in the advance setting in your app.
Access tokens are portable. It's possible to take an access token generated on a client by Facebook's SDK, send it to a server and then make calls from that server on behalf of the client. An access token can also be stolen by malicious software on a person's computer or a man in the middle attack. Then that access token can be used from an entirely different system that's not the client and not your server, generating spam or stealing data.
You can prevent this by adding the appsecret_proof parameter to every API call from a server and enabling the setting to require proof on all calls. This prevents bad guys from making API calls with your access tokens from their servers. If you're using the official PHP SDK, the appsecret_proof parameter is automatically added.
Please refer the below url to generate the valid appsecret_proof,and add it to each api call
https://developers.facebook.com/docs/graph-api/securing-requests
I had to deal with the same issue while working with passport-facebook-token,
I finally released that the problem had nothing to have with the logic of my codebase or the app configuration.
I had this error just because I was adding intentionally an authorization Header to the request. so if you are using postman or some other http client just make sure that the request does not contain any authorization Header.

Google api php client code not return refresh token

I have been trying to get refresh token from google api using javascript google client " code " that google return from client side. It returns me the code which i send to the server side. Now from server side i am sending the code to get the refresh token and access token using using google-api-php-client with this call :
https://www.googleapis.com/oauth2/v4/token
While i use the same code from google playground i get the response with refresh token as well but i do not get it from my own server..
This is the code
public function getRefreshToken($code)
{
$client = new Google_Client();
$client->setClientId(config('services.google.client_id'));
$client->setClientSecret(config('services.google.client_secret'));
$client->setRedirectUri('postmessage');
$client->setScopes(config('services.google.scopes'));
$client->setAccessType("offline");
$client->setApprovalPrompt("force");
dd($client->authenticate($code));
dd($client->getRefreshToken());
return ;
}
I have set access type to offline as mentioned in some answers but still i get the response with our refresh token.. this is the response
access_token :"xxxxxxxxxxxxxxxxxxxxxx"
created:1510242052
expires_in:3598
id_token:"xxxxxxxx"
token_type:"Bearer"
Your php code looks fine to me. I suspect your front end javascript, specifically the link to google that it builds, may be to blame. Whether the authorization_code produces a refresh token when redeemed is partially dependent on what parameters are included in the initial link to Google.
As detailed in this answer, the javascript client library uses "client side flow". Normally in a front end app you'd specify response_type=token, but if you specify response_type=code, instead, you'll get a code back. But when redeemed, that code will not produce a refresh token.
For example, a link built by a front end javascript library might look like this:
https://accounts.google.com/o/oauth2/v2/auth?client_id=7xxxxxxxxxxx-xxxxxxxxxxx.apps.googleusercontent.com&redirect_uri=http://localhost:8080/oauth2callback.php&response_type=code&scope=profile
Your back end can redeem the code that comes back, but the response will not include a refresh token. This is by design.
One way to get a code that is eligible for refresh tokens, would be to use the back end PHP client library to build the link, rather than the javascript client library. $client->createAuthUrl() will build a link like this:
https://accounts.google.com/o/oauth2/auth?response_type=code&access_type=offline&client_id=7xxxxxxxxxx-hxxxxxxxxxxxxxxxx.apps.googleusercontent.com&redirect_uri=http%3A%2F%2Flocalhost%3A8080%2Foauth2callback.php&state&scope=profile&approval_prompt=force
This toy example builds the link this way and does receive refresh tokens.
Note the addition of access_type=offine and approval_prompt=force. After successful authentication, the redirect in this case includes a code that does provide a refresh token when redeemed.
The OAuth 2.0 playground builds an initial link that contains access_type=offline and prompt=consent, which also creates a code that is redeemable for a refresh token.
If this isn't helpful, perhaps you could update the question with the link to google that your front end is building? (With client id redacted, of course)

Categories