I can not retrieve data from twitter even after generating a Bearer code. An example of a request is:
var url = "https://api.twitter.com/1.1/statuses/show.json?id=1125750390664892417";
var bearer = 'Bearer '+ 'myBearer code';
fetch(url, {
method: 'GET',
withCredentials: true,
credentials: 'include',
headers: {
'Authorization': bearer,
'Content-Type': 'application/json'}
}).then((anyResponse) => {
console.log(anyResponse);
}) .catch(error => console.log('Something bad happened ' + error.message)
);
I do not understand what could be possibly wrong, but It always fails. I have obtained the bearer code following this page (https://developer.twitter.com/en/docs/basics/authentication/guides/bearer-tokens). But I did not encode any of my keys (as I have read here it was necessary, but the twitter page doesnt say so). Does somebody have an idea what could possibly go wrong with my request ???
Thanks!
For me, it finally worked in Postman when I used the bearer code without the base64 encryption. However, It goes against the docu and the nice python coded commented by a user above.
I still did not implement in my JS code, but since it is working is Postman, I can imagine that any XHR request with the same credentials should also work. Thanks for the help!
Related
I'm trying to make a GET request from the instructure-canvas API that requires a bearer token. I'm able to do so via both Postman and a curl command they provided me with:
curl -H "Authorization: Bearer <ACCESS-TOKEN>" "https://canvas.instructure.com/api/v1/courses"
Both these methods work and I am returned with the proper json data. However, I was wondering if there exists a way of doing this same operation in JavaScript (with or without additional libraries/frameworks). Apologies if this is trivial, I am very new to working with API's.
If you're making the request from the browser, you can use the Fetch API. It'll look a little something like this:
const url = ""; // API URL
const token = ""; // API Token
const method = "GET"; // Request method, change for what's needed
fetch(url, {
method,
headers: {
"Authorization": `Bearer ${token}` // This is the important part, the auth header
}
}).then(res => res.json().then(console.log)).catch(console.error); // Do better handling here
Depending on the server setup, you may need additional headers. Also keep an eye on the console for errors relating to CORs, as once again they will differer depending on how the server has been configured.
I'm trying to get an OAuth token for the Reddit API following the Application Only OAuth instructions. My reddit app is an installed app, so for my grant_type I'm using https://oauth.reddit.com/grants/installed_client.
Currently I'm running a very short JS script to query the API and get a token:
const APP_ID = 'MY_APP_ID'
const DEVICE_ID = 'TRACKING_ID_20_TO_30_CHARS'
let form = new FormData()
form.append('grant_type', 'https://oauth.reddit.com/grants/installed_client')
form.append('device_id', DEVICE_ID)
fetch('https://www.reddit.com/api/v1/access_token', {
method: 'POST',
headers: new Headers({
'Content-Type': 'application/x-www-form-urlencoded',
'Authorization': `Basic ${btoa(`${APP_ID}:`)}`,
}),
body: form })
.then(handleResponse)
.then(function(data) {
console.log(data)
})
.catch(error => console.error(error))
function handleResponse(response) {
return response.json()
}
(Note: running the snippet as-is will give you a NetworkError because the APP_ID isn't a real one and I don't want to give mine out.)
The response I get is:
{
"error": "unsupported_grant_type"
}
When I try the same API request using a REST client I get back the expected response, so this makes me think that the problem is JavaScript-related. Since the grant_type matches what the instructions say I'm not really sure what to do with the error. I'm hoping someone else more experienced with OAuth will know what is going on here.
The problem was the use of the FormData object. In earlier stages of troubleshooting I found this answer on Reddit and decided to use it, but that didn't work for me.
It was submitting the data as multipart/form-data rather than application/x-www-form-urlencoded, which Reddit's OAuth server did not like. I wrote a helper function based on this answer which did the trick:
function urlEncode(data) {
let out = [];
for (let key in data) {
out.push(`${key}=${encodeURIComponent(data[key])}`);
}
return out.join('&')
}
What is the best way with pure javascript fetch function to check if JWT has expired that is being passed in authorization header before making a request to get data?
const headers = new Headers({
'Content-Type': 'application/json',
Authorization: 'Bearer GrabbedFromParamQueryString'
});
const settings = {
method: 'GET',
headers: headers
};
fetch('/info/user, settings).then(response => {
console.log(response.json());
});
I know in jQuery you can do a precheck if it has expired then generate a new token then continue with the original request. Is there something like that with Javascript fetch if so how?
Any help would be appreciated.
I was able to achieve this by checking the status of the response which gave me the answer if it was expired or not. Once I had that information created a handled error function and do the next set of action to grab the new refresh and token id.
try
console.log(response.json());
if(response.msg=== "Token is expired"){
alert('token is already expired, login again')
}
});
Atleast thats what I do for jwt extended tokens , because they generate such a response. so in your case, If you used some other naming type like "message" please go ahead and use it to loop through your response. I hope its been of help.
return fetch(`{SERVICE API URL}`, {
method: 'GET',
headers: {
'userName': "username",
'password': "password",
'content-type': 'application/json'
}
})
.then(response => response.json())
.then(json => dispatch(receivePosts(reddit, json)))
I'm trying to get service API data with authorization headers, but getting 401 - Unauthorized error and the response is Missing Request Headers.
Tried with sending authorization content with body also - getting same error 401 - Unauthorized error.
Edited:
headers: {
'userName': "xyz",
'sessionToken': "xyz................."
}
When I'm checking with Postman client it is working fine, but not with the redux-saga fetch method. Kindly help me for this.
Looks like it's a backend problem - CORS Filter configuration
If the backend is on a different server (could be on the same machine, but in a different Application Server, in other words, on a different port) you have to do some CORS Filters configurations.
The frontend code is running on a server - that means it's an application. Postman is a client, just like Google Chrome or any other browser. That's the explanation why you can do the request without any problem from Postman but unsuccessful from your frontend application.
I guess you enabled the Access-Control-Allow-Origin header on the backend
Now you have to allow your custom headers with Access-Control-Allow-Headers
Whenever I use fetch and I need to add headers to the request I do it this way:
headers: new Headers({
Accept: 'application/json',
Authorization: token,
'Content-Type': 'application/json',
}),
so you might want to try this approach, also in order to debug this issue you might want to check your Netowrk tab and verify which headers are sent with the request.
You need to add an Authorization bearer header.
For instance:
headers = new Headers({
'Authorization': `Bearer ${authorizationCodeOrCredentials}`
});
In your code:
return fetch(`{SERVICE API URL}`, {
method: 'GET',
headers: {
'Authorization': 'Bearer ' + someValue, // Add this line
'userName': "username",
'password': "password",
'content-type': 'application/json'
}
})
.then(response => response.json())
.then(json => dispatch(receivePosts(reddit, json)))
If you are using Linux system & If you have chrome in it...
Run your chrome using following command
/opt/google/chrome/chrome --disable-web-security --user-data-dir
Try now, If everything works fine then it's CORS issue from Backend.
I need to validate Bigcommerce legacy API credentials using AJAX (more precisely, using $http in AngularJS)
Every time I post a request to a store api, I always get the response:
[{"status":401,"message":"No credentials were supplied in the request."}]
I've tried every combination of parameters and headers that I can think of, and still I get the same error message. I could not find a single example of javascript code to validate the old Bigcommerce API credentials (legacy API).
Please help!
Bigcommerce clients provide the following data:
username, api_path, api_token
Here is my code:
var encoded_access_token = window.btoa(unescape(encodeURIComponent(
$scope.merchant.username + ':' + $scope.merchant.api_token
)));
$scope.merchant.api_path = 'https://store-ji3ql.mybigcommerce.com/api/v2/time';
$http({
method: 'GET',
url: $scope.merchant.api_path,
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json, application/xml, text/plain',
'Authorization': 'Basic ' + encoded_access_token
},
isArray: false
}).success(function(returnData) {
console.log('success!');
console.log(returnData);
}).error(function(returnData) {
console.log('error!');
console.log(returnData);
});
As I know, you could not validate Bigcommerce legacy API credentials with JS but a backend language such PHP, Ruby, ...
You could employ BC's APIs on you own server with PHP then expose it for JS code to call from.
(I have not implemented on my own, but that's what I heard from a bigcommerce developer)
Please visit this for more information: https://developer.bigcommerce.com/api/clients