'Missing or duplicate parameters' in Access Token Response - node.js

I'm trying to fetch the OAuth access token with the lambda function but getting fhe following error:
data: {
error: 'invalid_request',
error_description: 'Missing or duplicate parameters'
}
This is the code:
var axios = require("axios").default;
exports.handler = async (event) => {
var options = {
method: 'POST',
url: 'https://******/auth/oauth/v2/token',
headers: {'content-type': 'application/x-www-form-urlencoded'},
data: {
grant_type: 'client_credentials',
client_id: '*********',
client_secret: '******'
}
};
try {
const resp = await axios.request(options);
console.log(resp.data)
} catch (err){
console.error(err);
}
};
When I try to run the request with the Postman it returns the valid token.

As stated by #derpirscher, I had to properly serialize the data object using 'qs' library. After that I was able to fetch the access token successfully.
var axios = require("axios").default;
const qs = require('qs');
exports.handler = async (event) => {
var data = {
grant_type: 'client_credentials',
client_id: '*********',
client_secret: '************'
};
var options = {
method: 'POST',
url: 'https://************/auth/oauth/v2/token',
headers: {'content-type': 'application/x-www-form-urlencoded'},
data: qs.stringify(data)
};
try {
const resp = await axios.request(options);
console.log(resp.data)
} catch (err){
console.error(err);
}
};

Related

axios post request getting error 500 fdretdrgfdg

A post request with axios get http error 500.
This is the code:
async function getUserTokenByRefresh(refreshToken) {
const encodedStr = base64Encode(`${process.env.EBAY_SANDBOX_APPID}:${process.env.EBAY_SANDBOX_CERTID}`);
const auth = `Basic ${encodedStr}`;
const options = {
headers: {
"Content-Type": "application/x-www-form-urlencoded",
Authorization: auth
}
};
const data = {
grant_type: "refresh_token",
refresh_token: refreshToken
};
const testing = true;
const url = testing
? "https://api.sandbox.ebay.com/identity/v1/oauth2/token"
: "https://api.ebay.com/identity/v1/oauth2/token";
try {
const response = await axios.post(
url,
data,
options
);
console.log(JSON.stringify(response));
}
catch (e) {
console.log(JSON.stringify(e));
}
}
This is the error message:
{
"message": "Request failed with status code 500",
"code": "ERR_BAD_RESPONSE",
"status": 500
}
This is the error message in json format.
I don't know what's wrong in the code.
Can you check it?
Data should be encoded.
async function getUserTokenByRefresh(refreshToken) {
const encodedStr = base64Encode(`${process.env.EBAY_SANDBOX_APPID}:${process.env.EBAY_SANDBOX_CERTID}`);
const auth = `Basic ${encodedStr}`;
const options = {
headers: {
"Content-Type": "application/x-www-form-urlencoded",
Authorization: auth
}
};
const data = {
grant_type: "refresh_token",
refresh_token: refreshToken
};
const testing = true;
const url = testing
? "https://api.sandbox.ebay.com/identity/v1/oauth2/token"
: "https://api.ebay.com/identity/v1/oauth2/token";
try {
const response = await axios.post(
url,
//ENCODED DATA
new URLSearchParams(data),
options
);
console.log(JSON.stringify(response));
}
catch (e) {
console.log(JSON.stringify(e));
}
}

Request succeeds with `request` but fails with `axios`

I have this microsoft graph authentication code, making what I think is the same request using axios and then using request. However, the axios request fails with 404, whereas the request request succeeds. What am I doing wrong with axios?
const axios = require('axios')
const request = require("request");
const FormData = require('form-data');
const data = FormData()
data.append('client_id', XXXXXXXXXXX),
data.append('client_secret', XXXXXXXXX),
data.append('scope', "https://graph.microsoft.com/.default"),
data.append('grant_type', 'client_credentials')
const requestParams = {
client_id: logins.activedirectory.clientID,
client_secret: logins.activedirectory.clientSecret,
scope: "https://graph.microsoft.com/.default",
grant_type: "client_credentials",
};
const endpoint = "https://login.microsoftonline.com/" + XXXXXXXX + "/oauth2/v2.0/token";
///////// AXIOS //////////
axios({
method: 'post',
url: endpoint,
data: data,
headers: {'Content-Type': 'application/x-www-form-urlencoded' }
})
.then(function (response) {
console.log(response);
})
.catch(function (response) {
console.log(response);
});
///////// REQUEST /////////
request.post({ url:endpoint, form: requestParams }, function (err, response, body) {
if (err) {
console.log(err);
} else {
console.log(body);
}
});

Discord Ouath2 Access Token 'Grant type None is not supported'

Im trying to make a login system with discord for my website that is made with express. I have made a function to get an access token so that I can use that function in the route.
Im trying to get an access token from: https://discord.com/api/oauth2/token
Here is my code:
async GetToken(code) {
let access_token;
const payload = {
'client_id': client_id,
'client_secret': client_secret,
'grant_type': 'authorization_code',
'code': code,
'redirect_uri': redirect_uri,
'scope': scope,
};
const config = {
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
};
fetch(discord_token_url, {
method: 'post',
body: payload,
headers: config.headers,
}).then(response => response.json()).then(json => console.log(json)).catch(err => console.log(err));
return access_token;
},
And here's the err I get:
{
error: 'unsupported_grant_type',
error_description: 'Grant type None is not supported'
}
As you can see I've given the correct grant type yet I get this error.
Forgot to update to add the solution and saw a lot of people looking at this so here's the solution (thanks to #Kira):
You have to use URLSearchParams
// Modules
const fetch = require('node-fetch');
const { url } = require('inspector');
const { URLSearchParams } = require('url');
// Add the parameters
const params = new URLSearchParams();
params.append('client_id', client_id);
params.append('client_secret', client_secret);
params.append('grant_type', 'authorization_code');
params.append('code', code);
params.append('redirect_uri', redirect_uri);
params.append('scope', scope);
// Send the request
fetch('https://discord.com/api/oauth2/token', {
method: 'post',
body: params,
headers: { 'Content-Type': 'application/x-www-form-urlencoded', 'Accept': 'application/json' },
}).then(r => r.json()).then(Response => {
// Handle it...
handle()
});

Got error when trying to get access token in nodejs using azure, AADSTS50058: A silent sign-in request was sent but no user is signed in

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

Try to fetch Instagram access token with all required params but still get an error code 400

This is the server side code that tried to make a POST request to Instagram to get an access token
app.get('/instagram/json', (req, res) => {
axios({
method: 'post',
url: 'https://api.instagram.com/oauth/access_token',
data: {
'client_id': instagramClientId,
'client_secret': instagramClientSecret,
'grant_type': 'authorization_code',
'redirect_uri': 'http://localhost:3000',
'code': instagramCode
}
}).then((response) => {
console.log(response);
}).catch((e) => {
console.log(e);
});
});
This is the error response I get. It tells me that "client_id" is required despite I clearly have provided it.
data:
{ error_type: 'OAuthException',
code: 400,
error_message: 'You must provide a client_id' } } }
Here is a solution:
const insta_form = new URLSearchParams();
insta_form.append('client_id', 'xxx');
insta_form.append('client_secret', 'xxx');
insta_form.append('grant_type', 'authorization_code');
insta_form.append('redirect_uri', 'xxx');
insta_form.append(
'code',
'xxx'
);
await axios({
method: 'POST',
url: 'https://api.instagram.com/oauth/access_token',
data: insta_form,
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
})
.then((response) => {
console.log(response);
})
.catch((err) => {
console.log(err.response);
});
}
import axios from 'axios'
import {stringify} from 'qs'
const response = await axios({
method: "post",
url: "https://api.instagram.com/oauth/access_token",
data: stringify({
client_id: CLIENT_ID,
client_secret: CLIENT_SECRET,
grant_type: 'authorization_code',
redirect_uri: REDIRECT_URL,
code
}),
headers: { "Content-Type": 'application/x-www-form-urlencoded' },
})
Late, but since there's not a good answer on the web and took me a while:
You'd have to wrap your body inside a form-data before providing it to fetch-node's post.
Install form-data: npm install --save form-data
then:
const formData = require("form-data");
const insta_form = new formData();
insta_form.append("client_id", your client id);
insta_form.append("client_secret", your client secret);
insta_form.append("grant_type", "authorization_code");
insta_form.append("redirect_uri", your redirect uri);
insta_form.append("code", user code);
const shortTokenRes = await fetch(
"https://api.instagram.com/oauth/access_token",
{
method: "POST",
body: insta_form,
}
);

Resources