Can't get Angular $resource to send proper Headers - javascript

I'm building a prototype Angular app, using Parse as a temporary RESTful back end (Until the real restful backend is completed)
I've setup a Factory with $resource() but I'm constantly getting a 401 unauthorized.
Right now my factory looks like this (APPIDKEY AND APIKEY are redacted of course)
app.factory('eventFactory', ['$resource', function($resource){
return $resource('https://api.parse.com/1/classes/Events',{},
{headers:{"X-Parse-Application-Id": "APPIDKEY",
"X-Parse-REST-API-Key": "APIKEY"}});
}
]);
I've also tried writing the $resrouce like this.
$resource('https://myAppID:javascript-key=myJavaScriptKey#api.parse.com/1/classes/Events');
But that also returns a 401. however if I copy and paste that URL into my browser the screen prints out all the objects in the request.
I've done extensive googling and read the $resource docs many times but I still can't quite figure this out. I'm thinking it has to do with Cross-Origin policy but the parse documentation says
'For Javascript usage, the Parse Cloud supports cross-origin resource sharing, so that you can use these headers in conjunction with XMLHttpRequest.' So I'm kinda stumped.
Any help is much appreciated. Thanks!

Adding these two lines inside my module.config function fixed it.
$httpProvider.defaults.headers.common['X-Parse-Application-Id']="APPIDKEY"
$httpProvider.defaults.headers.common['X-Parse-REST-API-Key']="RESTAPIKEY"
where APPIDKEY and RESTAPIKEY equal the keys provided from Parse.com

Related

401 Unauthorized API

I've stumbled upon a problem whilst working on a weather app. I have 401 error popping up every time i'm trying to fetch API from openweathermap.com. I've tried everything so far to fix this problem like waiting some days until my API key would work for me. I also tried to create a new API key and use it but failed at it again. Finally i tried to create another account on openweathermap.com but still have this error. Can anyone help me to find out what is the problem?
P.S. i used a valid API for checking a basic weather info that is available for free subscribtion.
401 Error screenshot
Your API Key is provided as a value to query parameter: appid is wrapped in {}. Remove those braces and perform the request again.
Very often, you will find the usage of {} in the documents, they represent placeholders in a string and are not meant to be part of the final string.
Weathermap Docs: How to make an API Call?
Also, please, make sure that you DO NOT share any essential API Keys in a public forum.
{} should be removed inside the url. It should be
let api = `https://api/openweathermap.org/data/2.5/weather?q=${city}&appid=e2850163218373000f889c28107ac0cf`

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.

Get an access token without being connected to facebook

I need to retrieve a facebook page's list of posts (feed) using their javascript SDK, just like they explain in their docs: https://developers.facebook.com/docs/graph-api/reference/v2.4/page/feed
/* make the API call */
FB.api(
"/{page-id}/posts",
function (response) {
if (response && !response.error) {
/* handle the result */
}
}
);
I need it to be my website's "news section", so users should see it even if they are not connected to facebook.
The problem
Cool, but there is a problem... It returns: An access token is required to request this resource.
Holy cow... I'd like to get some access token for you #facebook, but my app doesn't make use of your authentication tools/plugins.
ANYWAY, I tried with FB.getLoginStatus(); but doesn't work, because the only way it can return an access_token is if the user is actually connected to the application. My users may not even be logged to facebook!
So, ¿How can I get an access_token to be stored into a variable, and later be used to get /{my-page}/posts?
I've already payed a look to this SO question, but it doesn't solves my problem, simply because there are no such "generic tokens".
I've also read https://developers.facebook.com/docs/facebook-login/access-tokens/ and that also relies on tokens generated through facebook login methods... So, can't I display a list of fb page's posts in my website, without being connected into facebook, hence an application?
ADD: My app is build with angularJS, I'm not dealing with server-side code. I shall rely purely on javascript methods.
You could either use an page or an app access token, but as you'd be using them on the client-side, neither of them are an option.
See
https://developers.facebook.com/docs/facebook-login/access-tokens#apptokens
https://developers.facebook.com/docs/facebook-login/access-tokens#pagetokens
Note that because this request uses your app secret, it must never be made in client-side code or in an app binary that could be decompiled. It is important that your app secret is never shared with anyone. Therefore, this API call should only be made using server-side code.
I'd strongly recommend to build a simple server-side script (PHP for example) to proxy the request to the Graph API. You could then call this via AJAX for example and load the posts asynchronously (and alse get rid of the FB JS SDK!). There is NO way to handle this in a secure manner if you don't want to use FB Login for all of your users (which also doesn't make much sense IMHO).
I think it's straightforward :)
Since pages' posts are always public, it only needs a valid access token to retrieve page posts.
Quoting what you've written:
So, ¿How can I get an access_token to be stored into a variable, and later be used to get /{my-page}/posts?
You only require an access token.
My suggestion would be;
- Generate an access token for yourself (no extra permission needed)
- request page-id/posts
This way you don't require other users to be connected to facebook, you can simply requests page-id/posts to retrieve posts with access token you generated for yourself.
I hope it solves your problem :D
TIP: As long as posts are public, you only require a valid access token, it doesn't need to be user or page specific.

Facebook Graph API - #4 error - application request limit reached

I'm trying to get the number of likes from a Facebook page with the following line of code in JavaScript, but I get the "application request limit reached error" even though I only made one API call to a single FB page
var jsonData = UrlFetchApp.fetch("https://graph.facebook.com/" + name);
Request failed for https://graph.facebook.com/nba returned code 403.
Truncated server response: {"error":{"message":"(#4) Application
request limit reached","type":"OAuthException","code":4}} (use
muteHttpExceptions option to examine full response)
I'm confused on why this is happening and I've looked at similar questions on StackOverflow regarding this problem, but none seemed to give the right solution or point me in the right direction. Any help is appreciated. Thanks!
App Level Rate Limiting
This rate limiting is applied globally on application level. When the app uses more than allowed resources the error is thrown.
Recommendations:
Do not make multiple calls in small amount of time, spread out the calls throughout the day.
Do smart fetching of data, you can always fetch important data only, you can remove duplicate data as well
Use parameters: "since", "until", "limit" to limit/filter the requests
You can find out more in Official documentation here!

Soundcloud API /resolve method 404 error

Simple dimple one here- trying to use Soundcloud's resolve method to retrieve a JSON feed of track data for a private set.
http://api.soundcloud.com/resolve.json?url=http://soundcloud.com/myUser/private-set
resolve returns a 401 unauthorized error, as it should
http://api.soundcloud.com/resolve.json?url=http://soundcloud.com/myUser/private-set&client_id=myClientID
resolve returns a '404' not found error. it should be 301 redirecting to the authorized JSON feed for the track, such as http://api.soundcloud.com/tracks/49931.json in the doc's example
I've created an App
I'm using the App's Client ID
I've enabled App access in the Set's edit menu
I'm formatting it as per the API docs
Am I missing something here?
So after some testing I've confirmed that the issue is related to the fact that you're trying to request a private set. Because the set is private, you would need to first go through SoundCloud's OAuth 2 authentication process before being able to access the set.
Try resolving the set url with the url found in the share dialog of your set. This url contains a secret token that can be used to access a private set without logging in.
Not sure how far this'll get you if the tracks in the set are also private, though. And like bbone mentioned, you'll be exposing this secret token, which may or may not be a problem.

Categories