Axios login request: Unauthorized, request status code 401 - node.js

I'm trying to get an authorization token by making a request to an api using axios:
axios({
method: 'post',
url: 'http://62.110.134.187/api/signin',
headers: { 'content-type': 'application/x-www-form-urlencoded' },
auth: {
username: usr,
password: pwd
}
}).then(function (response) {
console.log(response)
}).catch(function (error) {
console.log('Error: ' + error)
})
I'm getting always status code 401(Unauthorized):
Error: Request failed with status code 401
Where I'm doing wrong?
The fact is that making the same request using python works fine:
payload = "username=%s&password=%s" % (usr,pwd)
headers = {'content-type': 'application/x-www-form-urlencoded'}
response = requests.request("POST", url_login, data=payload, headers=headers)
print(response.text)
data = response.json()
token = data["token"]

By sending username and password in auth: {} in axios, you are doing the basic-authentication, basically sending Authorization: basic <base64(user:pass)> header.
As per working python program, you need to send the username and password as part of the request body. You need to serialize the body params for url-encoded content type as well.
e.g.
const querystring = require('querystring');
axios({
method: 'post',
url: 'http://62.110.134.187/api/signin',
headers: { 'content-type': 'application/x-www-form-urlencoded' },
data: querystring.stringify({
username: usr,
password: pwd
})
}).then(function (response) {
console.log(response)
}).catch(function (error) {
console.log('Error: ' + error)
})

Related

Make Request With Node.JS To Change Vanity Discord

How can I change the vanity url code in Discord? My current code returns a 401 error.
Code:
const fetch = require("node-fetch");
setTimeout(async () => {
await fetch('https://www.discord.com/api/v9/guilds/serverID/vanity-url', {
method: 'POST',
headers: { 'Authorization': 'Bot ' + client.token, 'Content-Type': 'application/json'},
payload: JSON.stringify({
"code":"terbo1"
})
})
.then(async res => await res.json())
.then(json => { console.log(json);});
Response:
{ message: '401: Unauthorized', code: 0 }
I don't understand why you need setTimeout however you were using the wrong HTTP method on the request: the correct method is PATCH.
Additionally, payload isn't an option on the Fetch API, use body instead.
const fetch = require("node-fetch");
const endpoint = `https://www.discord.com/api/v10/guilds/${SERVER_ID}/vanity-url`;
await fetch(endpoint,{
method: "PATCH",
headers: {
Authorization: `Bot ${client.token}`,
"Content-Type": "application/json",
},
body: JSON.stringify({
code: "terbo1",
}),
});
Edit: As of 01/12/2022 (12/01/22) Discord have now disabled this ability for bots to "manipulate" this request, however, the above script can be used on a User-Account, there are risks of being banned doing so, so it is NOT recommended, use at your own risk.

Converting Curl to Nodejs Axios - Obtaining an Access Token

I am currently using curl in order to obtain an access token so I can consume an api with said token. The curl command I use is as follows:
curl --user <client_id>:<client_secret> https://api.ed-fi.org/v3/api/oauth/token --data 'grant_type=client_credentials'
It works and all...but instead of curling I want to utilize the axios library to get this access token instead.
Here's what I have but it doesn't work.
const buff = new Buffer.from('<client_id>:<client_secret>';
const base64data = buff.toString('base64');
axios({
method: 'POST',
url: 'https://api.ed-fi.org/v3/api/oauth/token',
headers: {
Authorization: `Basic ${base64data}`
},
data: { 'grant_type': 'client_credentials' }
})
.then(response => {
console.log(response);
})
.catch(error => {
console.log(error);
});
I can't figure out what I'm missing or doing wrong?
You should change Content-Type (default for axios is JSON) and pass body just like you did in case of curl:
axios({
method: 'POST',
url: 'https://api.ed-fi.org/v3/api/oauth/token',
headers: {
Authorization: `Basic ${base64data}`,
'Content-Type': 'application/x-www-form-urlencoded'
},
data: 'grant_type=client_credentials'
})
.then(response => {
console.log(response);
})
.catch(error => {
console.log(error);
});

Axios 400 Bad Request Cognito JWT generation in Node Js

I am trying to create Cognito JWtoken via POST call with axios in Lambda function using node js , but i am getting error 400 bad request.
In parallel it is working fine in Postman.
Code :
await axios.post('https://smartfactoryfabric-dev.auth.us-east-1.amazoncognito.com/oauth2/token', {
grant_type: grantType, // This is the body part
redirect_uri: redirectURI,
client_id: clientid,
code: 'fb06a2dd-XXXXXXXXX-f186c6302806'
}, {
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Authorization': 'Basic ' + authValue
}
})
.then(response => {
console.log(response)
})
.catch(error => {
console.log(error.response)
});
You need to URL encode the body of your request into a single string. You can use querystring.stringify to do this.
let data = querystring.stringify({
grant_type: 'grantType',
redirect_uri: 'redirectURI',
client_id: 'clientid',
code: 'fb06a2dd-XXXXXXXXX-f186c6302806'
})
=> 'client_id=clientid&code=fb06a2dd-XXXXXXXXX-f186c6302806&grant_type=grantType&redirect_uri=redirectURI'
Then your request will look like this:
await axios.post('https://smartfactoryfabric-dev.auth.us-east-1.amazoncognito.com/oauth2/token',
data,
{
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Authorization': 'Basic ' + authValue
}
})

Kannel HTTP POST fails

This is my NodeJS (request-promise) for sending SMS via HTTP GET with SMS gateway Kannel:
var options = {
method: 'GET',
uri: 'http://127.0.0.1:13002/cgi-bin/sendsms',
qs: {
username: 'foo',
password: 'bar',
to: '127883327304',
from: '12488331359',
text: 'Hi
}
};
This works, but changing to HTTP POST fails.
var options = {
method: 'POST',
uri: 'http://127.0.0.1:13002/cgi-bin/sendsms',
form: {
username: 'foo',
password: 'bar',
to: '127883327304',
from: '12488331359',
text: 'Hi
}
};
Getting body: 'Authorization failed for sendsms' } }
Also able to get: body: 'Invalid content-type' } }
But the content-type is correct http form: application/x-www-form-urlencoded.
...and tried old school XML:
var xml = ' \
<?xml version="1.0"?>\
<message>\
<submit>\
<da><number>11021034235</number></da>\
<oa><number>11076034723</number></oa>\
<ud>Hello</ud>\
<from>\
<user>foo</user>\
<username>foo</username>\
<pass>bar</pass>\
<password>bar</password>\
</from>\
</submit>\
</message>\
';
var options = {
method: 'POST',
uri: 'http://127.0.0.1:13002/cgi-bin/sendsms',
body: xml,
headers: {'content-type': 'text/xml'}
};
but getting: body: 'Authorization failed for sendsms' } }
I'm lost on what to do, and HTTP GET doesn't work for long SMSes.
Tried
request({
url: 'http://127.0.0.1:13002/cgi-bin/sendota',
method: 'POST',
headers : {
'content-type': 'text/xml',
'X-Kannel-Username': 'foo',
'X-Kannel-Password': 'bar',
'X-Kannel-To': '1324422133',
'X-Kannel-From': '12023455750'
},
body: xml
}, function (error, response, body) {
console.log('error:', error); // Print the error if one occurred
console.log('statusCode:', response && response.statusCode); // Print the response status code if a response was received
console.log('body:', body); // Print the HTML for the Google homepage.
});
Now I'm getting body: Unsupported content-type, rejected
but text/xml should be supported...

How to use bearer token for authorization for POST method in sync-request?

How can we use bearer token with POST method using npm sync-request? The sync-request resource page has the way to use authorization in GET request but not in POST request.
*******GET Request*******
var request = require('sync-request');
var res = request('GET', 'https://example.com', {
'headers': {
'user-agent': 'example-user-agent'
}
});
****POST Request*****
var request = require('sync-request');
var res = request('POST', 'https://example.com/create-user', {
json: { username: 'Name' }
});
Not sure why you would want to use sync-request which can cause timing issues but this should work with either sync-request or request
// *******GET Request*******
var request = require('sync-request');
var res = request('GET', 'https://example.com', {
'headers': {
'user-agent': 'example-user-agent',
'authorization', 'Bearer ' + authId
}
});
// ****POST Request*****
var request = require('sync-request');
var res = request('POST', 'https://example.com/create-user', {
'headers': {
'authorization', 'Bearer ' + authId
},
json: { username: 'Name' }
});
authId needs to be whatever your bearer token spoils be for your app.
I would suggest use of axis and example below:-
GET
import axios from "axios";
axios({
method: 'get',
url: url,
headers: {
'Content-Type': 'application/json'
}
}).then(function (response) {
console.log(response);
}).catch((err) => {
console.log(err)
));
POST
axios({
method: 'post',
url: url,
data: JSON.stringify({orders}),
headers: {
'Content-Type': 'application/json',
'Authorization': userObj.token
}
}).then(function (response) {
console.log(response)
});
Where ubserObj.token -
Bearer Token ex: Bearer ASDF#!##!ADFASDF!##!##
This will be on the server side settings.

Resources