I want to get the data of artists followed by a user, but when I make the request, it just gives me an error code 400, and the message 'Only valid bearer authentication supported'. I'm not sure what's wrong. Here's the code I'm using.
app.get('/callback', function(req, res) {
var code = req.query.code || null;
var state = req.query.state || null;
var storedState = req.cookies ? req.cookies[stateKey] : null;
if (state === null || state !== storedState) {
res.redirect('/#' +
querystring.stringify({
error: 'state_mismatch'
}));
} else {
res.clearCookie(stateKey);
var authOptions = {
url: 'https://accounts.spotify.com/api/token',
form: {
code: code,
redirect_uri: redirect_uri,
grant_type: 'authorization_code'
},
headers: {
'Authorization': 'Basic ' + (new Buffer(client_id + ':' + client_secret).toString('base64'))
},
json: true
};
request.post(authOptions, function(error, response, body) {
if (!error && response.statusCode === 200) {
var access_token = body.access_token,
refresh_token = body.refresh_token;
var options = {
url: 'https://api.spotify.com/v1/me/following?type=artist&limit=50',
headers: { 'Authorization': 'Bearer' + access_token },
json: true
};
request.get(options, function(error, response, body) {
console.log(body);
});
res.redirect('/#' +
querystring.stringify({
access_token: access_token,
refresh_token: refresh_token
}));
} else {
res.redirect('/#' +
querystring.stringify({
error: 'invalid_token'
}));
}
});
}
});
Related
Im using nodejs to make a call to a 3rd party API. My code code returns the correct data for an id that I'm passing in my backend. When I run my app, to retrieve the data I go to localhost:5000/api/Dls.
My code
app.get("/api/Dls", (req, res) => {
const response = {
success: false
};
if (req.user && Authorized.myToken) {
response.success = true;
response.data = {};
response.data.user = req.user;
const id = response.data.user.sub;
var options = {
method: 'GET',
url: 'https://someApi/byId/' + 'id',
headers:
{
Accept: 'application/json',
Authorization: 'Bearer' + ' ' + Authorized.myToken
}
};
request(options, function (error, response, body){
if (error) {
console.log(error);
return;
}
const data = response.body;
const userDls = JSON.parse(data)
return res.json(userDls);
});
}
});
Now I'm trying to do something like this localhost:5000/api/Dls/1234 instead of using a hard coded id in the backend
I attempted doing the following but when I enter a valid id in the url (ex. localhost:5000/api/Dls/1234) I get this "", any idea to what I should be doing?
app.get("/api/Dls/:id", (req, res) => {
const response = {
success: false
};
if (Authorized.myToken) {
response.success = true;
var options = {
method: 'GET',
url: 'https://someApi/byId/',
headers:
{
Accept: 'application/json',
Authorization: 'Bearer' + ' ' + Authorized.myToken
}
};
request(options, function (error, response, body){
if (error) {
console.log(error);
return;
}
const data = response.body;
const userDls = JSON.parse(data)
return res.json(userDls);
});
}
});
Any feedback would be appreciated!
You are not passing the route id to the api.
response.success = true;
var options = {
method: 'GET',
url: 'https://someApi/byId/' + req.params.id,
headers:{
Accept: 'application/json',
Authorization: 'Bearer' + ' ' + Authorized.myToken
}
};
I am using the node.js + request for send HTTP request to URL. I required the JSON response, but I get junk character.
Here is my node.js code
var request = require('request');
var post_data = { UserName: "xxxxx", Password: "xxxxx" };
var post_options = {
url: 'http://xxxxxxx.info/api/CoreUser/cognitoLogin',
method: 'POST',
form: post_data,
headers: {
'AppID': 'zNiphaJww8e4qYEwJ96g555HTAAbAXdj',
'OAuth': 'xxxxxxxxxxxxxxxxxx',
//'User-Agent': 'Super Agent/0.0.1',
'Content-Type': 'application/json;charset=UTF-8',
}
};
// Set up the request
request(post_options, function (error, response, body) {
console.log(response.statusCode);
if (!error && response.statusCode == 200) {
console.log("200");
console.log(response);
}
});
But I received response in junk characters.
I need result in jSON format, What is wrong in this request?
I found the issue, reason is that API response send in gZip format. Here is the change we have to made here. Just enable gzip: true that resolve the things.
var request = require('request');
var post_data = { UserName: "xxxxx", Password: "xxxxx" };
var post_options = {
url: 'http://xxxxxxx.info/api/CoreUser/cognitoLogin',
method: 'POST',
gzip: true,
form: post_data,
headers: {
'AppID': 'zNiphaJww8e4qYEwJ96g555HTAAbAXdj',
'OAuth': 'xxxxxxxxxxxxxxxxxx',
//'User-Agent': 'Super Agent/0.0.1',
'Content-Type': 'application/json;charset=UTF-8',
}
};
// Set up the request
request(post_options, function (error, response, body) {
console.log(response.statusCode);
if (!error && response.statusCode == 200) {
console.log("200");
console.log(response);
}
});
You are missing { json: true } in request call
request(post_options, { json: true }, function (error, response, body) {
console.log(response.statusCode);
if (!error && response.statusCode == 200) {
console.log("200");
console.log(response);
}
});
I am trying to implement azure login in nodejs scheduler app, and then want to upload file to share point.
First i need to login, then get access token,refresh token, admin access token etc.
When i try to get access token , i got error like this.
Here no use of any front end.
URL= 'https://login.microsoftonline.com/' + TENANT_ID + '/oauth2/token',
Status Code Error: 400 -
"{"error":"invalid_grant","error_description":"AADSTS50058: A silent sign-in request was sent but no user is signed in.\r\nTrace ID: 05db5c6a-155c-4870-9bca-a518b5931900\r\nCorrelation ID: 1e8372d0-c1ba-4070-88d7-597e9cb5cb2c\r\nTimestamp: 2019-08-14 12:04:42Z","error_codes":[50058],"timestamp":"2019-08-14 12:04:42Z","trace_id":"05db5c6a-155c-4870-9bca-a518b5931900","correlation_id":"1e8372d0-c1ba-4070-88d7-597e9cb5cb2c","error_uri":"https://login.microsoftonline.com/error?code=50058\"}"
Here the code
async function init(parsedBody) {
var jwtToken = await sharepointAuth.getJWTToken(parsedBody);
console.log("jwtToken:",jwtToken)
const config = {
JWK_URI: appConstants.JWK_URI,
ISS: appConstants.ISS,
AUD: appConstants.conf.AUD,
};
console.log(config)
await azureJWT.verify(jwtToken, config).then(async () => {
console.log("----------------------------------")
var fileName = 'analytics.min.js';
var filePath = './public/analytics.min.js';
var userAccessToken = await getAccessToken(jwtToken);
console.log("userAccessToken:", userAccessToken);
var accessTokenObj = await sharepointAuth.getAdminAccessToken();
accessToken = accessTokenObj.access_token;
console.log("accessToken:", accessToken)
fs.readFile(filePath, { encoding: null }, function (err, data) {
const relativeUrl = web/GetFolderByServerRelativeUrl('${selectedFolderName}');
const SHAREPOINT_HEADER = {
'Authorization': Bearer ${accessToken},
"Content-Type": application/json;odata=verbose,
'Accept': 'application/json;odata=verbose',
}
const options = {
method: "POST",
uri: ${SHAREPOINT_URI}${relativeUrl}/Files/add(url='${fileName}',overwrite=true),
headers: SHAREPOINT_HEADER,
body: data
};
console.log(options)
rp(options)
.then(() => {
// POST succeeded...
console.log('File uploaded!');
})
.catch((error) => {
// POST failed...
console.log("File Upload Error: ", error.toString());
});
});
});
}
const request = require("request");
const endpoint = "https://login.microsoftonline.com/tenentId/oauth2/token";
const requestParams = {
grant_type: "client_credentials",
client_id: "ClientId",
client_secret: "Secret",
resource: "ClientId"
};
request.post({ url: endpoint, form: requestParams }, function (err, response, body) {
if (err) {
console.log("error");
}
else {
console.log("Body=" + body);
let parsedBody = JSON.parse(body);
if (parsedBody.error_description) {
console.log("Error=" + parsedBody.error_description);
}
else {
console.log("parsedBody : " + parsedBody);
console.log("Access Token=" + parsedBody.access_token);
init(parsedBody);
}
}
});
function getAccessToken(jwtToken) {
return new Promise(async (resolve) => {
try {
const options = {
method: 'POST',
uri: URL,
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
formData: {
grant_type: appConstants.OTB_GRANT_TYPE,
client_id: appConstants.conf.AUD,
client_secret: appConstants.conf.CLIENT_SECRET,
resource: appConstants.OTB_RESOURCE_URI2,
client_assertion_type: appConstants.OTB_CLIENT_ASSERTION_TYPE,
requested_token_use: appConstants.OTB_REQ_TOKEN_USE,
scope: appConstants.OTB_SCOPE,
assertion: jwtToken,
},
};
console.log("options:", options)
await rp(options)
.then(async (parsedBody) => {
// POST succeeded...
const result = JSON.parse(parsedBody);
console.log("****************************************** result", result)
refreshToken = result.refresh_token;
resolve(result.access_token);
})
.catch((error) => {
// POST failed...
console.log('getAccessTokenRequestError: ', error.toString());
resolve(appConstants.ACCESS_TOKEN_ERROR);
});
} catch (error) {
console.log('getAccessTokenRequestPromiseError: ', error.toString());
resolve(appConstants.MIDDLEWARE_ERROR);
}
});
}
I have no idea about azure login without front end. I want to login in azure and upload file to share point in scheduler app in node.
First i need to login by using client id and secret. then i got bearer token. then i want to get access token by using bearer token. At that time i get error like this.
AADSTS50058: A silent sign-in request was sent but no user is signed in
Why don't you get the access token this way(client credentials flow)?
const request = require("request");
const endpoint =
"https://login.microsoftonline.com/{tenant}/oauth2/token";
const requestParams = {
grant_type: "client_credentials",
client_id: "",
client_secret: "",
resource: "https://mydomain.sharepoint.com"
};
request.post({ url: endpoint, form: requestParams }, function(
err,
response,
body
) {
if (err) {
console.log("error");
} else {
console.log("Body=" + body);
let parsedBody = JSON.parse(body);
if (parsedBody.error_description) {
console.log("Error=" + parsedBody.error_description);
} else {
console.log("Access Token=" + parsedBody.access_token);
}
}
});
If you need the access token which contains login user message, you can use ROPC flow.
const request = require("request");
const endpoint =
"https://login.microsoftonline.com/{tenant}/oauth2/token";
const requestParams = {
grant_type: "password",
username: "",
password: "",
client_id: "",
resource: "https://mydomain.sharepoint.com"
};
request.post({ url: endpoint, form: requestParams }, function(
err,
response,
body
) {
if (err) {
console.log("error");
} else {
console.log("Body=" + body);
let parsedBody = JSON.parse(body);
if (parsedBody.error_description) {
console.log("Error=" + parsedBody.error_description);
} else {
console.log("Access Token=" + parsedBody.access_token);
}
}
});
I am Creating REST API Call in jira using below code :-
var loginArgs = {
data: {
"username": "singhharwinder#seasiainfotech.com",
"password": "Seasia#123"
},
headers: {
"Content-Type": "application/json"
}
};
client.post("http://jira.atlassian.com/rest/auth/1/session",
loginArgs,function (data, response) {
if (response.statusCode == 200) {
console.log('succesfully logged in, session:', data.session);
var session = data.session;
var searchArgs = {
headers: {
cookie: session.name + '=' + session.value,
"Content-Type": "application/json"
},
data: {
jql: "type=Bug AND status=Closed"
}
};
client.post("http://jira.atlassian.com/rest/api/2/search", searchArgs, function (searchResult, response) {
console.log('status code:', response.statusCode);
console.log('search result:', searchResult);
});
} else {
throw "Login failed :(";
}
});
It is giving me "Reference Error: client is not defined".
Please help me .
I'm currently building a node implementation of the new Box View API and I'm getting a 202 everytime I upload a document and retrieve a session. However, if I do a curl call, I dont get a 202. Is there anyone else experiencing this issue?
Here is my Ember Implementation:
export default Ember.View.extend({
document: null,
documentID: null,
session: null,
sessionID: null,
getDocument: function() {
var self = this;
return Ember.$.ajax({
url: 'http://localhost:3000/doc',
type: 'POST',
contentType: 'application/json',
dataType: 'json',
data: JSON.stringify({ "docURL": this.textField.value })
}).then(function(response){
self.set('document', response);
self.set('documentID', response.document_id);
});
},
getSession: function() {
var self = this;
return Ember.$.ajax({
url: 'http://localhost:3000/sess/',
type: 'POST',
contentType: 'application/json',
data: JSON.stringify({ "docID": this.get('documentID') })
}).
then(function(response) {
self.set('session', response);
self.set('sessionID', response.session_id);
});
}.observes('documentID'),
actions: {
upload: function() {
this.getDocument();
}
}
});
Here is my node implementation:
var https = require('https');
var requestCount = 0;
exports.doc = function(req, res) {
var docURL = req.body.docURL;
var httpReq;
var opts = {
hostname: 'view-api.box.com',
path: '/1/documents',
method: 'POST',
headers: { 'Content-Type': 'application/json', 'Authorization': 'Token <my token>' }
};
res.header('Access-Control-Allow-Origin', '*');
httpReq = https.request(opts, function(preq, pres) {
var output = '';
preq.on('data', function(chunk) {
output += chunk;
});
preq.on('end', function() {
output = JSON.parse(output);
output.document_id = output.id;
delete output.id;
res.json(output);
});
});
httpReq.write(JSON.stringify({ "url": docURL }));
httpReq.end();
};
exports.sess = getSession;
function getSession(req, res) {
var docID = req.body.docID;
var httpReq;
var opts = {
hostname: 'view-api.box.com',
path: '/1/sessions',
method: 'POST',
headers: { 'Content-Type': 'application/json', 'Authorization': 'Token <my token>' }
};
res.header('Access-Control-Allow-Origin', '*');
httpReq = https.request(opts, function(preq, pres) {
var output = '';
if(preq.statusCode === 202) {
setTimeout(function() {
console.log('Retrying Request :: Count(' + requestCount + ')');
if (requestCount >= 3) {
res.json({ 'error': "Retry Again.", 'time': preq.headers['retry-after'] });
return;
}
getSession(req, res);
requestCount += 1;
}, 2000);
return;
}
preq.on('data', function(chunk) {
output += chunk;
});
preq.on('end', function() {
console.log('Successful Request!');
requestCount = 0;
output = JSON.parse(output);
output.session_id = output.id;
delete output.id;
res.json(output);
});
});
httpReq.write(JSON.stringify({ "document_id": docID, "duration": 60 }));
httpReq.end();
}
But now I'm getting this error. Is there a UI that can help me remove the uploaded documents?
{
"message": "You have exceeded your document upload rate-limit.",
"type": "error",
"request_id": "49f8b480b304496987b8cf21f5850c90"
}
You have the correct approach with retry-after for sessions.
The rate limiting you're seeing is actually due to the 2-document rate limit in place for the View API beta. See the FAQ for more info.
You can use webhooks to be notified when your documents finish converting (allowing you to upload another), so you don't have to poll the /documents endpoint for status.