403 Invalid token error on GET user info - desire2learn

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

Related

neo4j java cypher parameters not working

I am trying to create some dummy nodes in graph:
private final static Driver driver = GraphDatabase.driver("bolt://localhost:7687",
AuthTokens.basic("neo4j", "password"));
static Session session = driver.session();
String cypher = "CREATE "
+ "(:GPPocEntity {id:'{gppeid}',gppe_out_prop_1:'{gppe_out_prop_1_val_id}',"
+ "gppe_out_prop_2:'{gppe_out_prop_2_val_id}',"
+ "gppe_out_prop_X:'{gppe_out_prop_X_val_id}'})"
+ "-[:has]->"
+ "(:PPocEntity {id:'{ppeid}',ppe_out_prop_1:'{ppe_out_prop_1_val_id}',"
+ "ppe_out_prop_2:'{ppe_out_prop_2_val_id}',"
+ "ppe_out_prop_X:'{ppe_out_prop_X_val_id}'})"
+ "-[:contains]->"
+ "(:PocEntity {id:'{peid}',pe_out_prop_1:'{pe_out_prop_1_val_id}',"
+ "pe_out_prop_2:'{pe_out_prop_2_val_id}',"
+ "pe_out_prop_X:'{pe_out_prop_X_val_id}'})";
Map<String, Object> params = new HashMap<String, Object>();
int id = 1111;
params.put("gppeid","gppe"+id);
params.put("ppeid","ppe"+id);
params.put("peid","pe"+id);
params.put("gppe_out_prop_1_val_id","gppe_out_prop_1_val_"+id);
params.put("gppe_out_prop_2_val_id","gppe_out_prop_2_val_"+id);
params.put("gppe_out_prop_X_val_id","gppe_out_prop_X_val_"+id);
params.put("ppe_out_prop_1_val_id","ppe_out_prop_1_val_"+id);
params.put("ppe_out_prop_2_val_id","ppe_out_prop_2_val_"+id);
params.put("ppe_out_prop_X_val_id","ppe_out_prop_X_val_"+id);
params.put("pe_out_prop_1_val_id","pe_out_prop_1_val_"+id);
params.put("pe_out_prop_2_val_id","pe_out_prop_2_val_"+id);
params.put("pe_out_prop_X_val_id","pe_out_prop_X_val_"+id);
session.run(cypher, params);
But this does not set those parameters in cypher. Why is this so?
The problem is that you wrap the parameters in the cypher-query in single quotes, so they are not interpreted. Try to correct the query by removing single quotes:
String cypher = "CREATE "
+ "(:GPPocEntity {id:{gppeid}, gppe_out_prop_1: {gppe_out_prop_1_val_id}, "
+ " gppe_out_prop_2: {gppe_out_prop_2_val_id}, "
+ " gppe_out_prop_X: {gppe_out_prop_X_val_id}}) "
+ "-[:has]->"
...
A cypher parameter is $ + name, not { + name + }.
So for parameter called gppe_out_prop_1_val_id, you should put $gppe_out_prop_1_val_id into your query.
And you don't need to put quotes around, paramters are typed, so Neo4j will do it for you.

Yahoo Oauth in Ruby API Request - Signature Invalid

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)

Getting cookie stored in Javascript in Ruby on Rails

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=/'

JQUERY call to Controller Action: String Parameter truncated if containing 'space' character

I have a view that accepts 2 string parameters and 2 date values. User hits search button and they get filtered output to the screen. This all works perfectly well until a user inputs a string with a space. i.e. they can search for 'waste' but not 'waste oil'.
Interestingly, in the latter, the parameter is ok from Javascript before the call is made. But on entering the controller code it goes form being 'waste oil' on client to 'waste'. When this happens the other parameters get set to NULL crashing the system.
I've tried replacing the spaces if present with '#' character then stripping out and putting back in ' ' on the controller side. This is a messy fudge and only appears to work with one parameter.
There must be a simple explanation for this parameter data loss, any comments much appreciated
Not sure a code example is needed but here it is anyway if it help:
My controller header :
public ActionResult IndexSearch(int? page, string searchText,string searchTextSite,string StartDate,string EndDate)
{
My HTML Javascript :
function Search(sSearchText,sSite) {
sSearchText = sSearchText.toString().replace(" ", "#");
sSite = sSite.toString().replace(" ", "#");
debugger;
alert($("#AbsolutePath").val() + "Waste.mvc/IndexSearch?searchText=" + sSearchText + "&searchTextSite=" + sSite + "&StartDate=" + $('#StartDate').val() + "&EndDate=" + $('#EndDate').val());
$("#ResultsList").load($("#AbsolutePath").val() + "Waste.mvc/IndexSearch?searchText=" + sSearchText + "&searchTextSite=" + sSite + "&StartDate=" + $('#StartDate').val() + "&EndDate=" + $('#EndDate').val(),
function() {
$('#LoadingGif').empty();
});
$('#LoadingGif').empty().html('<img src="' + $("#AbsolutePath").val() + 'Content/images/ajax-loader.gif" alt="Loading image" />');
}
You are not URL encoding your parameters when sending the AJAX request because you are using string concatenations when building the url. You could use the following technique in order to have properly encoded values:
var url = $('#AbsolutePath').val() + 'Waste.mvc/IndexSearch';
var data = {
searchText: sSearchText,
searchTextSite: sSite ,
StartDate: $('#StartDate').val(),
EndDate: $('#EndDate').val()
};
$('#ResultsList').load(url, data, function() {
$('#LoadingGif').empty();
});
Now you will get correct values on the server.

jQuery $.post - do I have to encode the URL parameter?

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) {.......});

Resources