Getting net::ERR_ABORTED 401 in my react app - javascript

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

Related

Express.js can't find token from header

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/

Can't authorize user in jwt - Node.js react.js

When user login , it should redirects to homepage and gets posts.
I make api call in react but it returns 401 unauthorized . If I do with same auth header on postman it returns proper data.
const getPosts = async () => {
await axios
.get("/api/post", {
headers: { authorization: "Bearer" + localStorage.getItem("token") },
})
.then((res) => setPosts(res.data));};
useEffect(() => {getPosts();},[]);
Server Side
router.get("/api/post", authToken, async (req: Request, res: Response) => {
const posts = await Post.find({ relations: ["user"] });
return res.json(posts);
});
middleware
const authToken = (req: Request, res: Response, next: NextFunction) => {
const token = req.headers.authorization?.split(" ")[1];
if (token == null) return res.sendStatus(401);
jwt.verify(token, "SECRET", (err, decode) => {
if (err) return res.sendStatus(403);
res.locals = { ...res.locals, token: decode };
next();
});
};
You are missing the whitespace in your headers:
headers: { authorization: "Bearer " + localStorage.getItem("token") }

passing header in axios error: 400 bad request

I am trying authorization to my react app using axios and that request works with postman but when I start react it gives me 400 bad request error
let user = JSON.parse(localStorage.getItem("user"));
let userName = user.userName;
let accessToken = user.accessToken;
console.log(accessToken);
let config = {
headers: {
'Authorization': 'Bearer ' + accessToken
}
}
console.log(config);
axios.post("http://localhost:8080/getUserType",config).then((response) => {
var res=response.data;
this.setState({loginValue:res.userType});
console.log(res.userType);
}).catch((err) => {
console.log(err);
})
}
console return this
Dashboard.js:32 Error: Request failed with status code 400
at createError (createError.js:16)
at settle (settle.js:17)
at XMLHttpRequest.handleLoad (xhr.js:61)
Maybe try to directly use the headers instead of encapsulating them in a config variable.
let user = JSON.parse(localStorage.getItem("user"));
let userName = user.userName;
let accessToken = user.accessToken;
console.log(accessToken);
let headers: {
'Authorization': 'Bearer ' + accessToken
};
console.log(config);
axios.post("http://localhost:8080/getUserType", { headers }).then((response) => {
var res=response.data;
this.setState({loginValue:res.userType});
console.log(res.userType);
}).catch((err) => {
console.log(err);
})
}

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

Node request how to handle sessions

I'm using node.JS with request module.
My problem is, I need to authenticate the user on every request because the session is destroyed outside of the .then((response) => {}) block.
How is it possible to save the created session in a class for later use?
I tried out everything without success.
Here is a not working code snippet
login() {
const getLoginUrl = 'https://www.demourl.com/'
const postLoginUrl = 'https://www.demourl.com/account/login/'
rp({
url: getLoginUrl,
jar: this.cookieJar,
method: 'GET'
})
.then((body) => {
var csrftoken = this.cookieJar.getCookies(getLoginUrl)[1].toString().split('=')[1].split(';')[0];
var args = {
url: postLoginUrl,
json: true,
method: 'POST',
data: {
username: this.username,
password: this.password
},
headers: {
'method': 'POST',
'path': '/account/login/',
'cookie': 'csrftoken=' + csrftoken,
},
jar: this.cookieJar,
resolveWithFullResponse: true
}
rp(args)
.then((response) => {
//Here is a valid session
//But how can I use this session in different functions?
console.log('Post demourl.com/account/login success');
})
.catch((error) => {
console.log('Post demourl.com/account/login error: ', error);
});
})
.catch((error) => {
console.log('Get demourl.com error: ', error);
});
}
you should use this function as a middleware and then attach what ever you want to attach in to your req
try in you main script do
'use strict'
const express = require('express');
const login = require('./login');
const app = express()
app.use(login);// use this if you want all your routes to check login or put it in a specific route
app.get('/', (req,res)=>{
//this route is only for loged in users
});
const server = http.createServer(app).listen(process.env.PORT);
module.exports = app;
and in your login script
const login = (req, res, next) => {
const getLoginUrl = 'https://www.demourl.com/'
const postLoginUrl = 'https://www.demourl.com/account/login/'
rp({url: getLoginUrl, jar: this.cookieJar, method: 'GET'})
.then((body) => {
var csrftoken = this.cookieJar.getCookies(getLoginUrl)[1].toString().split('=')[1].split(';')[0];
var args = {
url: postLoginUrl,
json: true,
method: 'POST',
data: {
username: this.username,
password: this.password
},
headers: {
'method': 'POST',
'path': '/account/login/',
'cookie': 'csrftoken=' + csrftoken,
},
jar: this.cookieJar,
resolveWithFullResponse: true
}
rp(args)
.then((response) => {
res.loginResponse = response; // save the response for later use
console.log('Post demourl.com/account/login success');
next();
})
.catch((error) => {
console.log('Post demourl.com/account/login error: ', error);
return res.send(error) //send the error
});
})
.catch((error) => {
console.log('Get demourl.com error: ', error);
return res.send(error) //send the error
});
}
module.exports = login
I never see this.cookieJar being defined. Make sure it's initialized somewhere:
this.cookieJar = request.jar();
If you only use a single cookieJar in your application, you could also use Request's global cookie jar by setting the option jar to true:
// Either by setting it as the default
const request = require('request').defaults({jar: true});
// Or by setting it on each request
request('www.example.com', { jar: true });

Categories

Resources