Can't get access token by call Meteor HTTP get request - node.js

Http token request description(Doc)
URL: https://demo.tld/connect/token
HTTP Verb: POST
HTTP Headers:
Authorization: Basic base64encode(clientId:clientSecret)
Content-Type: multipart/form-data
HTTP Body:
grant_type: client_credentials
My requested code:
try {
let endCodeOfAuth = 'Basic ' + new Buffer(clientId + ':' + clientSecret).toString('base64');
HTTP.post("https://demo.tld/connect/token", {
headers: {
'Authorization': endCodeOfAuth,
'Content-Type': 'multipart/form-data'
},
content: 'grant_type:client_credentials'
}, (error, res) => {
if (res) console.log("2. res", res );
else console.log("1. error", error);
});
return true;
} catch (error) {
return false;
}
Response:
statusCode: 500,
content: '',
headers: {
server: 'Kestrel',
'x-powered-by': 'ASP.NET',
date: 'Mon, 01 Jun 2020 11:54:59 GMT',
connection: 'close',
'content-length': '0'
},
data: null
}

Related

Node https request returns Missing or duplicate parameters

Trying to get a token from ADP's API.
const https = require('https')
const fs = require('fs')
require('dotenv').config()
var requestBody = JSON.stringify({
client_id: process.env.ADP_CLIENT_ID,
client_secret: process.env.ADP_CLIENT_SECRET,
grant_type: 'client_credentials',
});
const options = {
hostname: 'accounts.adp.com',
port: 443,
path: '/auth/oauth/v2/token',
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Content-Length': requestBody.length
},
cert: fs.readFileSync('certificate.pem'),
key: fs.readFileSync('private.key'),
agent: false,
}
console.debug(options)
const req = https.request(options, (res) => {
let response = ''
console.log('statusCode:', res.statusCode);
console.log('headers:', res.headers);
res.on('data', (chunk) => {
response += chunk
})
res.on('end', ()=>{
console.log('Body: ', JSON.parse(response));
})
}).on("error", (err) => {
console.error("Error: ", err.message);
});
req.write(requestBody)
req.end()
When the script runs, an error is returned from the service:
$ node ./get_token.js
{
hostname: 'accounts.adp.com',
port: 443,
path: '/auth/oauth/v2/token',
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Content-Length': 141
},
cert: <Buffer ... bytes>,
key: <Buffer ... bytes>,
agent: false
}
statusCode: 400
headers: {
'adp-correlationid': 'XXX',
'x-ca-err': '3003103',
'cache-control': 'no-store',
pragma: 'no-cache',
'content-type': 'application/json;charset=UTF-8',
'content-length': '84',
date: 'Wed, 18 Jan 2023 17:50:06 GMT',
connection: 'close',
server: 'ADP API'
}
body: {
error: 'invalid_request',
error_description: 'Missing or duplicate parameters'
}
What am I missing or duplicating?
I needed to correctly serialize the requestBody:
...
const qs = require('querystring');
...
var requestBody = qs.stringify({
client_id: process.env.ADP_CLIENT_ID,
client_secret: process.env.ADP_CLIENT_SECRET,
grant_type: 'client_credentials',
});
which generated the expected response:
{
access_token: 'aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee',
token_type: 'Bearer',
expires_in: 3600,
scope: 'api'
}

Push notification send fails on server with 401 error

I am developing KaiOS application with web push notification capability.
While following code works on Chrome and current Mozilla it fails on KaiOS.
NodeJS code:
const push = require('web-push');
const vapidKeys = {
publicKey: 'PUBLIC_KEY',
privateKey: 'PRIVATE_KEY',
};
push.setVapidDetails(
'valid#email.com',
vapidKeys.publicKey,
vapidKeys.privateKey
);
const pushSub = {
endpoint: 'https://push.kaiostech.com:8443/wpush/v2/gAAAAABgNqjxZulGGFU',
keys: {
auth: 'AUTH',
p256dh: 'P256dH',
},
};
KaiOS:
failed to send notification WebPushError: Received unexpected response code
at IncomingMessage.<anonymous> (/node_modules/web-push/src/web-push-lib.js:347:20)
at IncomingMessage.emit (events.js:327:22)
at endReadableNT (_stream_readable.js:1221:12)
at processTicksAndRejections (internal/process/task_queues.js:84:21) {
statusCode: 401,
headers: {
date: 'Thu, 25 Feb 2021 15:35:19 GMT',
'content-length': '15',
'content-type': 'text/plain; charset=utf-8',
connection: 'close'
},
body: '{"errno":"109"}',
endpoint: 'https://push.kaiostech.com:8443/wpush/v2/gAAAAABgNqjxZulGGFU-72vZJFv0avzqAZAdWd7FSwZBINZ8AvsEkxAU2J3AFcs0e4aEUIYxi8aSzCCn8ihUgof_nfLGyR8VBprtzgZEABf14rSb9RgGgwxQip6f2792pS0BcUawcerZbNstCotDYTXdNZ7jQvegfDHUEHvril1KeEeaMoi4nGk'
}
But on Mozilla (with appropriate key changes) it response is successful. Same on Chrome.
notification response: {
statusCode: 201,
body: '',
headers: {
'access-control-allow-headers': 'content-encoding,encryption,crypto-key,ttl,encryption-key,content-type,authorization',
'access-control-allow-methods': 'POST',
'access-control-allow-origin': '*',
'access-control-expose-headers': 'location,www-authenticate',
'content-type': 'text/html; charset=UTF-8',
date: 'Wed, 24 Feb 2021 20:38:35 GMT',
location: 'https://updates.push.services.mozilla.com/m/gAAAAABgNrlLgRnDfpaVmZjc6eqnAxoXkaYkTT4nKCTI1ZIBt62hfu2l3XvGr0F8HfvW54etByCQNSX89ubyBjd2VtXOTPqfsiC4-iDBWol9q9GRwiBSgjFc2M5-avDmrRpq9eCAsxlgGCzp2sRYRqvVDAQBHa8GznLzKmDE87rWZM6ItMiLS8PN0jqiSZFYMlqooeCK53QN',
server: 'nginx',
'strict-transport-security': 'max-age=31536000;includeSubDomains',
ttl: '2419200',
'content-length': '0',
connection: 'Close'
}
}
Here is client service worker code:
self.addEventListener('push', (event) => {
console.log('push event', event);
const title = event.data.text();
event.waitUntil(self.registration.showNotification(title));
});
Any ideas, what could be a problem?
push.sendNotification(pushSub, 'hello my name is me', {
contentEncoding: 'aesgcm'
})
.then(function (res) {
console.log('notification response: ', res);
})
.catch(function (err) {
console.error('failed to send notification', err);
});
https://github.com/web-push-libs/web-push/issues/603
This server push.kaiostech.com require authorization. It allows access from KaiOS device only.

Why is res.header() not working in express?

I am trying to authenticate a user for login. However, I don't manage to send a response header.
Login function
// POST /users/login
router.post('/users/login', async (req, res) => {
try {
const body = _.pick(req.body, ['email', 'password']);
const user = await User.findByCredentials(body.email, body.password);
const token = await user.generateAuthToken();
req.session['token'] = 'Bearer ' + token;
req.session['user'] = user;
// the following line does not seem to work properly
res.header('Authorization', 'Bearer ' + token).send(user);
} catch (err) {
res.status(401).json({ message: "Nutzerdaten sind nicht korrekt" });
}
});
Axios plugin
$axios.onResponse(res => {
console.log(res.headers) // does not return an authorization header
if (res.headers.authorization) {
store.commit('auth/SET_TOKEN', res.headers.authorization)
}
return res
})
console.log(res.headers)
'x-powered-by': 'Express',
vary: 'Origin',
'access-control-allow-credentials': 'true',
'content-type': 'application/json; charset=utf-8',
'content-length': '2',
etag: 'W/"2-l9Fw4VUO7kr8CvBlt4zaMCqXZ0w"',
date: 'Tue, 30 Jul 2019 12:35:00 GMT',
connection: 'keep-alive'
I would be very thankful for any kind of help!

FCM legacy API call responded with JSON_PARSING_ERROR: Unexpected token END OF FILE at position 0

I am trying to implement the legacy call to FCM server where the response is unexpected. There it shows the Parsing Error which is not traceable for me as of now. I am posting the code snippet below. Please help me out if anything is missing or coded in wrong manner.
var request = require('request');
let message = {
"to": atoken,
"data": {
title: "My first push notification",
body: "Hello World!!!"
}
};
// //let message = req.body.message;
let key = "AIzaSyA1zIxVFJ3F7-_-XXXXXXXXXXXXXXXXXXX";
request({
method: 'POST',
uri: 'https://fcm.googleapis.com/fcm/send',
headers: {
'Content-type': 'application/json',
'Authorization': 'key=' + key
},
postData: JSON.stringify(message)
},
function (error, response, body) {
if (error) {
console.error('upload failed:', error);
res.status(500).json({ error: true, data: { message: error.message } });
} else {
let data = response;
console.log('Upload successful! Server responded with:',
data.toJSON());
//res.status(200).json(response);
}
});
The response coming is:
body:
'JSON_PARSING_ERROR: Unexpected token END OF FILE at position 0.\n',
headers:
{ 'content-type': 'text/plain; charset=UTF-8',
date: 'Tue, 16 Apr 2019 06:34:05 GMT',
expires: 'Tue, 16 Apr 2019 06:34:05 GMT',
'cache-control': 'private, max-age=0',
'x-content-type-options': 'nosniff',
'x-frame-options': 'SAMEORIGIN',
'x-xss-protection': '1; mode=block',
server: 'GSE',
'alt-svc': 'quic=":443"; ma=2592000; v="46,44,43,39"',
'accept-ranges': 'none',
vary: 'Accept-Encoding',
connection: 'close' },
request:
{ uri:
Url {
protocol: 'https:',
slashes: true,
auth: null,
host: 'fcm.googleapis.com',
port: 443,
hostname: 'fcm.googleapis.com',
hash: null,
search: null,
query: null,
pathname: '/fcm/send',
path: '/fcm/send',
href: 'https://fcm.googleapis.com/fcm/send' },
method: 'POST',
headers:
{ 'Content-type': 'application/json',
Authorization: 'key=AIzaSyA1zIxVFJ3F7-_-hrIbTHTehNRmTUwG8Z0',
'content-length': 0 } } }
Try changing postData: JSON.stringify(message) in request.post() to body: JSON.stringify(message).

digisigner document api gives Bad Request error if I call it with axios

DigiSigner is working fine if I call it from the postman, but it is giving error Bad Request if I call it with axios form nodejs application.
Here is my code sample.
const digi_signer_url = "https://api.digisigner.com/v1/documents";
const digi_signer_options = {
method: 'POST',
headers: { "Content-Type": "multipart/form-data", 'Authorization': `Basic ${process.env.DIGI_SIGNER_KEY}` },
data: {file: file},
url: digi_signer_url,
}
const r = axios(digi_signer_options)
Here is the solution.
const opts = {
method: 'POST',
url: 'https://api.digisigner.com/v1/documents',
headers:
{
'cache-control': 'no-cache',
authorization: `Basic ${process.env.DIGI_SIGNER_KEY}`,
'content-type': 'multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW'
},
formData:
{
file:
{
value: fs.createReadStream(path.join(__dirname, '../../templates/sample-po.pdf')),
options: { filename: 'sample-po.pdf', contentType: null }
}
}
};
request(opts, function (error, response, body) {
if (error) throw new Error(error);
if (body) {
const document = JSON.parse(body);
const {document_id} = document;
const send_to_signature = {
method: 'POST',
url: 'https://api.digisigner.com/v1/signature_requests',
headers:
{
'cache-control': 'no-cache',
'content-type': 'application/json',
authorization: `Basic ${process.env.DIGI_SIGNER_KEY}`
},
body:
{
documents:
[{
document_id: document_id,
subject: subject,
message: content,
signers:
[{
email: to_email,
fields: [{ page: 0, rectangle: [0, 0, 200, 100], type: 'SIGNATURE' }]
}]
}]
},
json: true
};
request(send_to_signature, function (error, response, result) {
if (error) throw new Error(error);
console.log(result)
});
}
});

Resources