Express.js can't find token from header - javascript

I have a problem in my authentication.js file where for some reason it can't access the token from the header but I have checked that I passed it on the front end. I also used postman and everything seems to work fine so I am sure that the problem is in the authentication.js file where when I try to console.log the token it's undefined.Below is the code:
const token = localStorage.getItem("token");
const jwt = require("jsonwebtoken");
module.exports = (req, res, next) => {
const token = req.get("authorization");
console.log(token); // Logs the token as undefined
if (!token || token === "") {
req.isAuth = false;
return next();
}
try {
let decoded = jwt.verify(token, process.env.JWT_SECRET);
req.duser = decoded.user;
res.status(200).send("Access granted.");
} catch (error) {
return res.status(403).send("Token is not valid.");
}
req.isAuth = true;
return next();
};
Also here is how I call the API:
const token = localStorage.getItem("token");
const { data } = await axios.post(
"/messages",
{
headers: {
Authorization: token
},
}
);

Please change this
headers: { Authorization: token },
to this
headers: { "Authorization": `Bearer ${token}`, "Content-Type": "application/json" },
in your api call
Do not forget to add data param as the second param. It's your request body.
axios
.post(
`/messages`,
data,
{
headers: {
"Authorization": `Bearer ${token}`, //mind the space before your token
"Content-Type": "application/json"
}
}
);
e.x. data
{
"firstname": "Firat",
"lastname": "Keler"
}
And then in the backend, check your token like that
const token = req.headers.authorization.split(' ')[1];
if (!token) {
//your logic
}

may be that your token isnt a Base64 String via client-side. Hope this helps
const temp = localStorage.getItem("token");
const token = Buffer.from(tmp, 'utf8').toString('base64')
axios.post('/messages', {
headers: {
'Authorization': `Basic ${token}`
}
});
RESOURCE:
https://flaviocopes.com/axios-send-authorization-header/

Related

Sending X-Auth-Token in header using axios

Using axios I want to send a request with X-Auth-Token in header.
Which one is the correct solution for doing this:
const url = `https:/.../${sku_id}/tokens/${token}`;
const result = await axios.post(url, { headers: { 'X-Auth-Token': token } });
Or this one:
const result = await axios.post(url, { headers: { 'Authorization': `token ${token}` } });

Pusher Beam beamsClient.setUserId always gets {"error":"Unauthorized","description":"Invalid JWT signature"}

I am implementing Pusher Beam Notification in our application and I always get a 401 error response when calling beamsClient.setUserId. I can verify that the JWT token generated is correct. Any idea why?
Here is the code I'm using:
const token = "****";
const instanceId = "****";
const currentUserId = "****";
const beamsTokenProvider = new PusherPushNotifications.TokenProvider({
url: "https://our-domain/pusher-beam-auth/",
headers: {
"Authorization": "Token " + token,
"Content-Type": "application/json"
}
});
const beamsClient = new PusherPushNotifications.Client({
instanceId: instanceId,
});
beamsClient
.start()
.then(() => beamsClient.setUserId(currentUserId, beamsTokenProvider)) // I always get 401 error here
.catch(console.error);
This answer only as per docs.
const currentUserId = "****";
const token = "****";
const instanceId = "****";
const tokenProvider = new PusherPushNotifications.TokenProvider({
url: 'https://our-domain/pusher-beam-auth/',
headers: {
Authorization: 'Token ' + token,
'Content-Type': 'application/json',
},
});
PusherPushNotifications.init({
instanceId: instanceId,
})
.then(beamsClient => beamsClient.start())
.then(beamsClient => beamsClient.setUserId(currentUserId, tokenProvider))
.then(() => console.log('Successfully authenticated with Pusher Beams'))
.catch(console.error);

Getting net::ERR_ABORTED 401 in my react app

Below is my react code snippet. I have verified that the token is correct using postman. Does anyone have ideas what might be missing here ?
export async function getData() {
const url = buildUri();
const auth = "Bearer " + await getAccessToken(); // api call to get access token
console.log("Using auth: ", auth);
var res = fetch(url, {
method: 'GET',
mode: 'no-cors',
headers: {
"Content-Type": "application/json",
"Authorization": auth
}
}).then(response => {
return response.json();
}).catch((error) => {
console.log("Error getting data: ", error);
});
console.log('got res: ', res);
}

Nodejs .Unable to send oauth v1 params in get request with axios

I wanted to make a request to ADP with autho1.0a
I was able to make successful requests as I wanted in postman but not through my application.
postman screenshot
npm module used
similar post
Code I tried
Part:1 Signature generation
const crypto = require('crypto')
const OAuth = require('oauth-1.0a')
const oauthObj = {};
function hash_function_sha1(base_string, key) {
return crypto
.createHmac('sha1', key)
.update(base_string)
.digest('base64')
}
oauthObj.getSignature = async payload => {
const { consumerKey,consumerSecret,apiUrl,method} = payload;
const oauth = OAuth({
consumer: { key: `${consumerKey}`, secret: `${consumerSecret}` },
signature_method: 'HMAC-SHA1',
hash_function: hash_function_sha1,
});
const request_data = {
url: `${apiUrl}`,
method: `${method}`
}
const token = {}
// return oauth.toHeader(oauth.authorize(request_data, token));
console.log('header string-----',oauth.toHeader(oauth.authorize(request_data, token)));
return oauth.authorize(request_data, token);
}
module.exports = oauthObj;
Part 2 : Axios Call
let oauthData=`oauth_consumer_key=${consumerKey}&oauth_signature_method=HMAC-SHA1&oauth_timestamp=${oauthTimestamp}&oauth_nonce=${oauthNonce}&oauth_version=1.0&oauth_signature=${oauthSignature}= HTTP/1.1`;
const eventData = await axios({
url:`${apiUrl}?${oauthData}`,
// url:`${apiUrl}?${oauthHeader.Authorization}`,
method:'GET',
headers:{
// ...oauthHeader,
'Authorization':'OAuth',
'Accept': 'application/json',
// "Authorization": `'OAuth oauth_consumer_key="${consumerKey}", oauth_nonce="${oauthNonce}", oauth_signature="${oauthSignature}", oauth_signature_method="HMAC-SHA1", oauth_timestamp="${oauthTimestamp}", oauth_version="1.0"`
}
});
Expected Result:
{
"code": "Gone",
"message": "Event with token 954c183f-26e0-4f9e-b452-c089aaf9842f has already been consumed."
}
Receiving error:
response: {
status: 401,
statusText: 'Unauthorized',
headers: {
What might have gone wrong ?
Try using request node package oauth option
request.get(`${apiUrl}?${oauthData}`, {
oauth: {
consumer_key: '..',
consumer_secret: '..',
},
headers: {
Accept: 'application/json'
},
}, function (err, res, body) {
console.log(body);
})

OAuth "unsupported_grant_type" Discord API

I'm trying to make the discord OAuth work. In the doc, it is necessary to generate a code, it works very well this step but after it is to generate the token. It asks to make a POST request with the right parameters but it always brings me the error: {"error":"unsupported_grant_type"}
My code:
app.get('/discord/callback', async function (req, res) {
if (req.query.code === undefined || req.query.code == '') return next();
const response = await fetch("https://discordapp.com/api/v6/auth2/token", {
method: 'POST',
headers: {
"Content-type": "application/x-www-form-urlencoded"
},
data: {
client_id: process.env.CLIENT_ID,
client_secret: process.env.CLIENT_SECRET,
code: req.query.code,
redirect_uri: redirect,
grant_type: "authorization_code",
scope: "identify"
}
});
const json = await response.json();
debug('%O', json);
res.send(json);
});
Doc:
def exchange_code(code):
data = {
'client_id': CLIENT_ID,
'client_secret': CLIENT_SECRET,
'grant_type': 'authorization_code',
'code': code,
'redirect_uri': REDIRECT_URI,
'scope': 'identify email connections'
}
headers = {
'Content-Type': 'application/x-www-form-urlencoded'
}
r = requests.post('%s/oauth2/token' % API_ENDPOINT, data, headers)
r.raise_for_status()
return r.json()
Thanks for your help
Your headers are:
headers = {
'Content-Type': 'application/x-www-form-urlencoded'
}
which means that it also expects the data as form data and NOT json.
So this should work:
app.get('/discord/callback', async function (req, res) {
if (req.query.code === undefined || req.query.code == '') return next();
const params = new URLSearchParams();
params.append('client_id', process.env.CLIENT_ID);
params.append('client_secret', process.env.CLIENT_SECRET);
params.append('grant_type', 'authorization_code');
params.append('code', code);
params.append('redirect_uri', redirect);
params.append('scope', 'identify');
const response = await fetch("https://discordapp.com/api/v6/auth2/token", {
method: 'POST',
body: params
headers: {
"Content-type": "application/x-www-form-urlencoded"
},
});
const json = await response.json();
debug('%O', json);
res.send(json);
});
You can refer this for better understanding: https://www.npmjs.com/package/node-fetch#post-with-form-parameters
I encountered this issue today as well, and inspired by Aakash Sharma's answer, I build a little utility function(in typescript) that will convert an object to that required format:
export const jsonToUrlParams = (data: Record<string, any>) => {
const params = new URLSearchParams();
for (const key in data) {
params.append(key, `${data[key]}`);
}
return params;
};

Categories

Resources