ExpressJS: Send Request Header Authentication - node.js

I have an API to authenticate the user with LDAP and I have been provided with the information which includes Content-Type: application/json and username and password for the request header and then the user's username and password to be passed in body. I tried the below code but it's not working. I want to know if I am passing the header request correctly or not.
router.post('/user', function(req, res){
var auth = {
content-type: "application/json",
username: "abcd",
password: "xyze"
}
auth.post('/user', {username: req.body.username, password: req.body.password"}, function(response) {
console.log(response);
})
})

Consider use axios package to make your requests: https://www.npmjs.com/package/axios
This link has a section “Creating an instance showing how you can set the header:
var instance = axios.create({
baseURL: 'https://some-domain.com/api/',
timeout: 1000,
headers: {'X-Custom-Header': 'foobar'}
});
Once the header is set, invoke the post method, like this:
instance.post('/my/specific/endpoint/', myData);
In the following example, you can pass an authentication token as the header to your request:
import axios from 'axios';
const MY_BASE_URL = 'https://www.myserver.com/';
class MyLdapService {
static xhr(accessToken) {
const options = {
baseURL: MY_BASE_URL,
headers: {
Authorization: `Bearer ${accessToken}`,
'Content-Type': 'application/json',
},
};
return axios.create(options);
}
static async myPostEndpoint(accessToken, data) {
return new Promise((resolve, reject) => {
this.xhr(accessToken).post('my-endpoint/', data)
.then(result => resolve(result.data.card))
.catch(err => reject(this.createError(err)));
});
}
}
So you can invoke the POST endpoint like this:
MyLdapService.myPostEndpoint('my_access_token', {});

Related

The accessToken I am getting from Auth0/NextJs not working on Routes

I am using #auth0/nextjs-auth0 for my nextJs login.
This is my /[auth0].js code:
import { handleAuth, handleLogin } from "#auth0/nextjs-auth0";
export default handleAuth({
login: handleLogin({
authorizationParams: {
audience: process.env.AUDIENCE,
}
})
});
After login, I am calling the getAccessToken() and what I get as token doesn't work with my endpoint. But when I copy test accessToken from auth0 dashboard, it will work.
import { getAccessToken, withApiAuthRequired, getSession } from "#auth0/nextjs-auth0";
export default withApiAuthRequired(async function users(req, res) {
try {
const { accessToken } = await getAccessToken(req, res);
const {user} = await getSession(req, res);
console.log("with access token …", accessToken);
const response = await fetch("http://localhost:7000/auth", {
headers: {
Authorization: `Bearer ${accessToken}`,
"Content-Type": "application/json",
},
method: "GET",
The response I always get is 401, Unathorized.
What am I doing wrong?

Axios POST request to Twillio returns with an Authentication Error?

in Node.js, I am trying to send a POST request with Axios to Twilio and send an SMS message to my phone. But I am getting an 'error: Authentication Error - No credentials provided ? Here is the code:
const body = {
'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8',
Body: 'hi from vsc',
To: toNumber,
From: fromNumber,
};
const headers = {
'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8',
Authorization: `Basic ${accountSID}:${authToken}`,
};
exports.axios = () => axios.post(`https://api.twilio.com/2010-04-01/Accounts/${accountSID}/Messages.json`, body, headers).then((res) => {
console.log(res, 'res');
}).catch((err) => {
console.log(err);
});
I also tried to use the same parameters with POSTMAN and the POST request is successful. I also tried to encode my authorization username and password to Base 64, but with no success.
I wrote to Twilio customer help but haven`t received any replies yet.
Axios makes an auth option available that takes an object with username and password options. You can use this with the username set to your account SID and password set to your auth token.
The headers object should be sent as the headers parameter of a config object in the third parameter to axios.post. Like so:
const params = new URLSearchParams();
params.append('Body','Hello from vcs');
params.append('To',toNumber);
params.append('From',fromNumber);
const headers = {
'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8',
};
exports.axios = () => axios.post(
`https://api.twilio.com/2010-04-01/Accounts/${accountSID}/Messages.json`,
params,
{
headers,
auth: {
username: accountSID,
password: authToken
}
}
}).then((res) => {
console.log(res, 'res');
}).catch((err) => {
console.log(err);
});
Headers is actually a field of config, try something like this:
const config = {
headers: {
'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8',
Authorization: `Basic ${accountSID}:${authToken}`,
}
}
axios.post(URL, data, config).then(...)
Or this (general example calling a Twilio endpoint)
const axios = require('axios');
const roomSID = 'RM1...';
const participantSID = 'PA8...';
const ACCOUNT_SID = process.env.ACCOUNT_SID;
const AUTH_TOKEN = process.env.AUTH_TOKEN;
const URL = "https://insights.twilio.com/v1/Video/Rooms/"+roomSID+"/Participants/"+participantSID;
axios({
method: 'get',
url: URL,
auth: {
username: ACCOUNT_SID,
password: AUTH_TOKEN
}
})
.then((response) => {
console.log(response.data);
})
.catch((error) => {
console.log(error);
});
Working code:
const params = new URLSearchParams();
params.append('Body','Hello from vcs');
params.append('To',toNumber);
params.append('From',fromNumber);
exports.axios = () => axios.post(
`https://api.twilio.com/2010-04-01/Accounts/${accountSID}/Messages.json`,
params,
{
auth: {
username: accountSID,
password: authToken,
},
},
).then((res) => {
console.log(res, 'res');
}).catch((err) => {
console.log(err);
});
The previous solutions did not work for me. I encountered either the Can't find variable: btoa error or A 'To' phone number is required..
Using qs worked for me:
import qs from 'qs';
import axios from 'axios';
const TWILIO_ACCOUNT_SID = ""
const TWILIO_AUTH_TOKEN = ""
const FROM = ""
const TO = ""
const sendText = async (message: string) => {
try {
const result = await axios.post(
`https://api.twilio.com/2010-04-01/Accounts/${TWILIO_ACCOUNT_SID}/Messages.json`,
qs.stringify({
Body: message,
To: TO,
From: FROM,
}),
{
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
auth: {
username: TWILIO_ACCOUNT_SID,
password: TWILIO_AUTH_TOKEN,
},
},
);
console.log({result});
} catch (e) {
console.log({e});
console.log({e: e.response?.data});
}
};

How to access and store the token and use it in other requests with Node.js?

I'm using the code below to authenticate myself and get a token.
It works perfectly.
const config = {
headers: { Authorization: 'Bearer ${token}' }
};
const bodyParameters = {
username: "teste",
senha: "123456"
};
axios.post(
'url ...',
bodyParameters,
config
).then(console.log).catch(console.log);
And the token below:
My question is: how to access this token and use it in another request?
For example, to get data from this API.
const config2 = {
headers: { Authorization: `Bearer ${token}` }
};
const bodyParameters2 = {
cpf: "12345",
hash: "912409kskllj1u2ou1p4124821"
};
axios.get(
'url..',
bodyParameters,
config
).then(console.log).catch(console.log);
In this case, I get error: 401 (unauthorized).
--UPDATE--
Update based on interceptors.
var LocalStorage = require('node-localstorage').LocalStorage,
localStorage = new LocalStorage('./scratch');
const api = axios.create({
baseURL: 'http://www.externalapi.com/', // this way you setup the static part of it and just call the instance with the rest of the specific route
});
api.interceptors.request.use(config => {
const token = localStorage.getItem('token');
if (token) {
config.headers['Authorization'] = `Bearer ${token}`;
}
return config;
});
exports.novaSolicitacao = (req, res) => {
const bodyParameters = {
username: "teste",
senha: "123456"
};
api.post(
'/login',
bodyParameters,
).then(console.log).catch(console.log);
const bodyParameters2 = {
cpf: "123456",
aceite: true,
};
app.get(
'/search',
bodyParameters2,
config
).then(console.log).catch(error);
I made this update to the code, but I get this error:
data: {
statusCode: 404,
error: 'SESSIONTOKENEXPIRED',
message: 'O token expirou.'
}
},
isAxiosError: true,
toJSON: [Function: toJSON]

Proxy API request through Express return pending Promise instead of response

I am currently trying to work with the Atlassian Jira rest API. In order to not get a CORS error I go through the recommended route of not sending the request from the browser but proxy it through my express server.
Now as I am doing this, all I receive back in the app is a pending promise. I assume that I have not correctly resolved it at one point but I cant figure out where.
API Handler sending the request to the proxy:
const baseURL = `${apiConfig}/jiraproxy`;
export const testConnection = integration => {
return fetch(`${baseURL}/get`, {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify(integration)
})
.then(handleResponse)
.catch(handleError);
};
Jira Proxy Endpoint on the Express Server
const baseURL = `rest/api/3/dashboard`;
router.post("/get", (req, res) => {
fetch(req.body.link + baseURL, {
method: "GET",
headers: { Accept: "application/json" },
auth: {
username: req.body.credentials.username,
password: req.body.credentials.token
}
})
.then(handleResponse)
.catch(handleError);
});
handleResponse & handle Error Methods:
async function handleResponse(response) {
if (response.ok) {
return response.json();
}
if (response.status === 400) {
const error = await response.text();
throw new Error(error);
}
throw new Error("Network response was not ok.");
}
function handleError(error) {
// eslint-disable-next-line no-console
console.error(`API call failed. ${error}`);
throw error;
}
Goal:
Send the request of sending a request to the proxy and return the resonse of the proxy as the return of the initial "testConction" method.
Error:
No errors thrown, but the response received in the Browser is a pending promise.
Change to the Jira Proxy router fixed it. Thanks to #jfriend00.
router.post("/get", (req, res) => {
return fetch(req.body.link + baseURL, {
method: "GET",
headers: { Accept: "application/json" },
auth: {
username: req.body.credentials.username,
password: req.body.credentials.token
}
})
// This is the part that changed
.then(response => handleResponse(response))
.then(jiraResponse => res.status(200).json(jiraResponse))
.catch(handleError);
});

Error handling axios request.post

We have an axios method like
export function callAcme(message) {
const requestUrl = `/api/acme/message`;
return {
type: ACME_MESSAGE,
promise: request.post(requestUrl, {
data: message
})
};
}
This method is mapped to an express router method, which makes a call to a third party API to get some data.
router.post("/acme/message", (req, res) => {
const { data } = req.body;
const url = "third/party/url/action;
authenticateThirdparty({
user: req.user
}).then(userToken => request({
method: "post",
url,
data: body,
baseURL: url,
"Content-Type": "application/json; charset=utf-8",
"Cache-Control": "no-cache",
headers: {
Authorization: `Bearer ${userToken}`
}
})).then((response) => {
res.status(200).send(response.data);
}).catch((error) => {
res.status(error.status).send(error.data);
});
});
The third party call is made in a try catch block. But id the third party method raises some error then we are are unable to send the error back to the web page who initiated the the axios call.
ie. In the client which invokes callAcme will not get the error object back.

Resources