I have already successfully gotten the access token and access secret. Now I'm trying to make an API request with the OAuth information.
I'm following alongside the yahoo docs (not very helpful):
https://developer.yahoo.com/oauth/guide/oauth-make-request.html
https://developer.yahoo.com/oauth/guide/oauth-signing.html
Also, I'm trying to follow this example closely:
https://gist.github.com/cheenu/1469815
Here is the code: (I split up the long url for convenience)
require 'cgi'
require 'base64'
require 'openssl'
url = "http://fantasysports.yahooapis.com/fantasy/v2/game/nfl"
parameters = "format=json
&realm=yahooapis.com
&oauth_consumer_key=#{Rails.application.secrets.yhoo_consumer_key}
&oauth_nonce=#{SecureRandom.hex}
&oauth_signature_method=HMAC-SHA1
&oauth_timestamp=#{Time.now.to_i}
&oauth_token=#{ApiVar.final_oauth_token} #the access token
&oauth_version=1.0"
base_string = 'GET&' + CGI.escape(url) + '&' + CGI.escape(parameters)
oauth_signature = CGI.escape(Base64.encode64("#{OpenSSL::HMAC.digest('sha1', ApiVar.final_oauth_secret + "&", base_string)}").chomp)
#ApiVar.final_oauth_secret is the access token secret - is that what I should be putting there?
testable_url = url + '?' + parameters + '&oauth_signature=' + oauth_signature
p testable_url
response = HTTParty.get(testable_url)
My response gives me "signature_invalid."
What am I doing wrong?
Thank you!
url = "http://fantasysports.yahooapis.com/fantasy/v2/league/{league-key}/players"
parameters = "format=json&oauth_consumer_key=#{Rails.application.secrets.yhoo_consumer_key}&oauth_nonce=#{SecureRandom.hex}&oauth_signature_method=HMAC-SHA1&oauth_timestamp=#{Time.now.to_i}&oauth_token=#{ApiVar.final_oauth_token}&oauth_version=1.0&realm=yahooapis.com"
base_string = 'GET&' + CGI.escape(url) + '&' + CGI.escape(parameters)
secret = "#{Rails.application.secrets.yhoo_consumer_secret}&#{ApiVar.final_oauth_secret}"
oauth_signature = CGI.escape(Base64.encode64("#{OpenSSL::HMAC.digest('sha1', secret, base_string)}").chomp)
testable_url = url + '?' + parameters + '&oauth_signature=' + oauth_signature
p testable_url
response = HTTParty.get(testable_url)
#{Rails.application.secrets.yhoo_consumer_secret}&#{ApiVar.final_oauth_secret}" - correct secret key
The parameters have to be ordered alphabetically! Also, the secret key is the yahoo consumer secret plus the final oauth secret!
The first thing that I can see as problematic is that the paremeters have a lot of whitespace that you do not want. Try the following instead:
parameters = "format=json" +
"&realm=yahooapis.com" +
"&oauth_consumer_key=#{Rails.application.secrets.yhoo_consumer_key}" +
"&oauth_nonce=#{SecureRandom.hex}" +
"&oauth_signature_method=HMAC-SHA1" +
"&oauth_timestamp=#{Time.now.to_i}" +
"&oauth_token=#{ApiVar.final_oauth_token}" +
"&oauth_version=1.0"
The other issue is that I do not believe your secret key needs the ampersand symbol added to it when you're creating the signature:
oauth_signature = CGI.escape(Base64.encode64("#{OpenSSL::HMAC.digest('sha1', ApiVar.final_oauth_secret, base_string)}").chomp)
Related
I am 100% sure that my client-id and client-secret are valid. I used it in my python code and it just worked fine
local http = require("coro-http")
local json = require("json")
local url = "https://id.twitch.tv/oauth2/token"
local client_id = "<>"
local client_secret = "<>"
local headers = {
["Content-Type"] = "application/x-www-form-urlencoded"
}
local body = "client_id=" .. client_id .. "&client_secret=" .. client_secret .. "&grant_type=client_credentials"
local response, w = http.request("POST", url, headers, body)
print(w)
local data = json.decode(w)
local access_token = data.access_token
local headers = {
["Client-ID"] = client_id,
["Authorization"] = "Bearer " .. access_token
}
local response, b = http.request("GET", "https://api.twitch.tv/helix/channels?broadcaster_id=141981764", headers)
print(b)
Getting token and then do a simple get request
I found this repository which is doing exactly what you're trying to.
From the code you provided and the one from the above repo, I would say #LMD comment is the way to go. You need to urlencode your body string.
Maybe querystring from luvit could be a good starting point.
UPDATE: I thought I had to pass the parameters as a JSON string in the request body, but actually I need to put them on the URL (the endpoint string), so it's working now.
I'm new to Valence. I have some Salesforce Apex code (written by someone else) that creates a D2L user. The code is working fine.
I want to add an Apex method to retrieve info for an existing D2L user using the userName parameter. I've copied the existing method, changed to a GET, set the query parameter to userName, and kept everything else the same.
When I call my method, I get a 403 Invalid Token error.
Do I need to use different authorization parameters for a GET? For example, do I still need to include a timestamp?
Here's a portion of the Salesforce Apex code:
public static final String USERS = '/d2l/api/lp/1.0/users/';
String TIMESTAMP_PARAM_VALUE = String.valueOf(Datetime.now().getTime()).substring(0,10);
String method = GETMETHOD;
String action = USERS;
String signData = method + '&' + action + '&' + TIMESTAMP_PARAM_VALUE;
String userSignature = sign(signData,USER_KEY);
String appSignature = sign(signData,APP_KEY);
String SIGNED_USER_PARAM_VALUE = userSignature;
String SIGNED_APP_PARAM_VALUE = appSignature;
String endPoint = DOMAIN + action + '?' +
APP_ID_PARAM + '=' + APP_ID + '&' +
USER_ID_PARAM + '=' + USER_ID + '&' +
SIGNED_USER_PARAM + '=' + SIGNED_USER_PARAM_VALUE + '&' +
SIGNED_APP_PARAM + '=' + SIGNED_APP_PARAM_VALUE + '&' +
TIMESTAMP_PARAM + '=' + TIMESTAMP_PARAM_VALUE;
HttpRequest req = new HttpRequest();
req.setMethod(method);
req.setTimeout(30000);
req.setEndpoint(endPoint);
req.setBody('{ "orgDefinedId"' + ':' + '"' + person.Id + '" }');
I thought I had to pass the parameters as a JSON string in the request body, but actually I need to put them on the URL (the endpoint string), so it's working now
Is there a way to get the cookie,set in JavaScript code, inside a controller method in Ruby on Rails v 4.0 ?
In a controller, you can set a cookie with:
cookies['foo'] = 'bar'
To set a cookie in Javascript, I wrote a short function in Coffeescript:
set_cookie: ( name, value, expiredays = 0 ) ->
expiredate = new Date()
expiredate.setDate expiredate.getDate() + expiredays
expire = '; expires=' + expiredate.toUTCString()
value = escape( value ) + expire
document.cookie = name + '=' + value + '; path=/'
I am having issues including the count parameter in the new Twitter Search API (Version 1.1) query. If I execute the query without the “count” parameter, I obtain the 15 default results. Meanwhile, if I include the count parameter, I obtain a 401 Unauthorized Error.
You will find hereafter, partial extracts from my code in C#.
1) Initially, the end of the baseString variable is set to “q=Test&count=100”.
2) After passing the baseString variable to the EscapeDataString function, the end becomes q%3DTest%26count%3D100, formatted in percent encoding, as expected.
3) Finally, the resource_url submitted is the following:
https://api.twitter.com/1.1/search/tweets.json?q=Test&count=100
var resource_url = "https://api.twitter.com/1.1/search/tweets.json";
var baseFormat = "oauth_consumer_key={0}&oauth_nonce={1}&oauth_signature_method={2}&oauth_timestamp={3}&oauth_token={4}&oauth_version={5}&q={6}&count={7}";
var baseString = string.Format(baseFormat,
oauth_consumer_key,
oauth_nonce,
oauth_signature_method,
oauth_timestamp,
oauth_token,
oauth_version,
Uri.EscapeDataString(q),
Uri.EscapeDataString(count)
);
baseString = string.Concat("GET&", Uri.EscapeDataString(resource_url), "&", Uri.EscapeDataString(baseString));
var postBody = "q=" + Uri.EscapeDataString(q) + "&count=" + Uri.EscapeDataString(count);
resource_url += "?" + postBody;
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(resource_url);
Would anyone have an idea why I am receiving this 401 Error?
I had similar issues, it seems when you Generate OAuth signature Twitter is fussy about the format of this string. I found even re-ordering the variables cause authentication errors.
Try replacing the specific lines in your code with the re-ordered ones below, hope that helps.
var resource_url = "https://api.twitter.com/1.1/search/tweets.json";
var tweet_query = "Test";
var tweet_count ="5";
var baseFormat = "count={7}&oauth_consumer_key={0}&oauth_nonce={1}&oauth_signature_method={2}&oauth_timestamp={3}&oauth_token={4}&oauth_version={5}&q={6}";
var baseString = string.Format(baseFormat,
oauth_consumer_key,
oauth_nonce,
oauth_signature_method,
oauth_timestamp,
oauth_token,
oauth_version,
Uri.EscapeDataString(tweet_query),
Uri.EscapeDataString(tweet_count)
);
var postBody = string.Format("q={0}&count={1}", Uri.EscapeDataString(tweet_query), Uri.EscapeDataString(tweet_count));
#JF0001
yes i have the same issue, but johnHk already have the correct answer. it's just placement issue.
when i use this, it doesn't work :
base_Format = "oauth_consumer_key={0}&oauth_nonce={1}&oauth_signature_method={2}" + "&oauth_timestamp={3}&oauth_token={4}&oauth_version={5}&q={6}&result_type={7}&count={8}"
but if i use this, it's work :
base_Format = "count={8}&oauth_consumer_key={0}&oauth_nonce={1}&oauth_signature_method={2}" + "&oauth_timestamp={3}&oauth_token={4}&oauth_version={5}&q={6}&result_type={7}"
look at the "count=" parameter, haha just re-order it into the first place.
I'm making an AJAX call with $.post(url, cb). The URL I'm passing in could potentially have weird characters like spaces, &, ? and so on.
Do I have to use $.post(encodeURIComponent(url), cb)?
url is something like /foo/weird-char§.
Do I have to use $.post(encodeURIComponent(url), cb)?
You will have to use encodeURIComponent() but not on the entire URI, only on the data part (weird and chars in your example). The URL and the ? & separating the parameters must stay intact. If you encode the entire URI, it will become unusable.
If you would add the data as POST data using the data parameter:
url = "/foo/possible";
$.post(url, { "weird": "f2(90§§$", "chars": "ß1028490" });
jQuery's Ajax functions would take care of URL encoding the data automatically.
Yes, you would need to encode the keys and values in the query string (but not the ? which separates the path from the query arguments and the & which separates the query arguments). This is built into jQuery if you use the data parameter of the $.post, like so:
$.post(url, { name: "John", time: "2pm" }, cb);
I'm using MVC3/EntityFramework as back-end, the front-end consumes all of my project controllers via jquery, posting directly (using $.post) doesnt requires the data encription, when you pass params directly other than URL hardcoded.
I already tested several chars i even sent an URL(this one http://www.ihackforfun.eu/index.php?title=update-on-url-crazy&more=1&c=1&tb=1&pb=1) as a parameter and had no issue at all even though encodeURIComponent works great when you pass all data in within the URL (hardcoded)
Hardcoded URL i.e.>
var encodedName = encodeURIComponent(name);
var url = "ControllerName/ActionName/" + encodedName + "/" + keyword + "/" + description + "/" + linkUrl + "/" + includeMetrics + "/" + typeTask + "/" + project + "/" + userCreated + "/" + userModified + "/" + status + "/" + parent;; // + name + "/" + keyword + "/" + description + "/" + linkUrl + "/" + includeMetrics + "/" + typeTask + "/" + project + "/" + userCreated + "/" + userModified + "/" + status + "/" + parent;
Otherwise dont use encodeURIComponent and instead try passing params in within the ajax post method
var url = "ControllerName/ActionName/";
$.post(url,
{ name: nameVal, fkKeyword: keyword, description: descriptionVal, linkUrl: linkUrlVal, includeMetrics: includeMetricsVal, FKTypeTask: typeTask, FKProject: project, FKUserCreated: userCreated, FKUserModified: userModified, FKStatus: status, FKParent: parent },
function (data) {.......});