that is my code in helper signin router
so I'm trying to set cookie to browser after confirm sign in
exports.signin = (req,res) => {
db.User.findOne({email:req.body.email}).then(user => {
user.comparePassword(req.body.password,function(err,isMatch){
if(isMatch){
let token = jwt.sign({userId: user.id},process.env.SECRET_KEY,{ expiresIn: 60*5 });
res.setHeader() //here I wanna send header Bearer to the browser
} else {
res.status(400).json({message:"Incorrect Password!"});
}
})
})
.catch(err => {
return res.status(404).send('No user found.');
})**strong text**
}
Authorization header is a client header, you cannot set it on the server(Server does not need authorization). You need to send it in a JSON response and then handle it in the client side.
Your server sends a JSON response with the token.
Your client sets the Authorization header and send it to any route that reaquires authorization
javascript client example:
var myHeaders = new Headers()
/**you need to get the token and put it in myToken var.
Where to store the token is the real question, you need
to take care about the storage you choose beacause of
the security risks*/
myHeaders.append('Content-Type','application/json; charset=utf-8');
myHeaders.append('Authorization', 'Bearer ' + myToken);
fetch( '/myurl', {
credentials: 'include',
headers: myHeaders,
method: 'GET'
}).then( res => {
return res.json();
}).then( res => {
/**your stuff*/
});
Then in your server check for the headers and you will see the Bearer
In Node.js res.setHeader() and Express js res.header() is an alias of res.set() method.
you can use in following ways :
res.setHeader('Authorization', 'Bearer '+ token);
res.header('Authorization', 'Bearer '+ token);
But I recommend you to read jwt example (angularjs & node) : https://code.tutsplus.com/tutorials/token-based-authentication-with-angularjs-nodejs--cms-22543
Related
I am trying to set up a simple login system for a small project. I have managed to connect the website to an login api hosted locally via mysql database.
I'm using express/nodejs on backend and Vue for front end. Also using axios to send http requests.
The error i get is POST http://localhost:3001/api/get-user 422 (Unprocessable Entity)
"{"message":"Please provide the token"}"
Client side part of code.
finally{
const auth = await axios.post(`/api/get-user`, {
headers: {
Authorization: `Bearer ${this.Token}`
}
})
}
Server side part.
router.post('/get-user', signupValidation, (req, res, next) => {
if(
!req.headers.authorization ||
!req.headers.authorization.startsWith('Bearer') ||
!req.headers.authorization.split(' ')[1]
){
return res.status(422).json({
message: "Please provide the token",
});
}
const theToken = req.headers.authorization.split(' ')[1];
const decoded = jwt.verify(theToken, 'the-super-strong-secrect');
db.query('SELECT * FROM users where id=?', decoded.id, function (error, results, fields) {
if (error) throw error;
return res.send({ error: false, data: results[0], message: 'Fetch Successfully.' });
});
});
I have put a base URL.
The login is working 100% and I am able to extract the token from the response data.
I used Postman to send the request to the server to get the user and it works perfectly. I believe the issue is in the code of the client side or maybe the client side is sending the token incorrectly where the server side cant read it... I'm not sure please help.
The second parameter in axios post is the body
finally{
const auth = await axios.post(`/api/get-user`,{}, {
headers: {
Authorization: `Bearer ${this.Token}`
}
})
}
I'm trying to call a api endpoint of my firebase functions hosted backend but I'm having an hard time.
This is the code of my endpoint:
app.post("/hello", (req,res) => {
console.log(req.headers);
res.status(200).json({
message: "Hello"
})
})
I'm also setting up a check for auth token with a middleware like so:
app.use(validateFirebaseIdToken);
const validateFirebaseIdToken = async (req,res,next) => {
console.log(req);
functions.logger.log('Check if request is authorized with Firebase ID token');
if ((!req.headers.authorization || !req.headers.authorization.startsWith('Bearer ')) &&
!(req.cookies && req.cookies.__session)) {
functions.logger.error(
'No Firebase ID token was passed as a Bearer token in the Authorization header.',
'Make sure you authorize your request by providing the following HTTP header:',
'Authorization: Bearer <Firebase ID Token>',
'or by passing a "__session" cookie.'
);
res.status(403).send('Unauthorized');
return;
}
let idToken;
if (req.headers.authorization && req.headers.authorization.startsWith('Bearer ')) {
functions.logger.log('Found "Authorization" header');
// Read the ID Token from the Authorization header.
idToken = req.headers.authorization.split('Bearer ')[1];
} else if(req.cookies) {
functions.logger.log('Found "__session" cookie');
// Read the ID Token from cookie.
idToken = req.cookies.__session;
} else {
// No cookie
res.status(403).send('Unauthorized');
return;
}
try {
const decodedIdToken = await admin.auth().verifyIdToken(idToken);
functions.logger.log('ID Token correctly decoded', decodedIdToken);
req.user = decodedIdToken;
next();
return;
} catch (error) {
functions.logger.error('Error while verifying Firebase ID token:', error);
res.status(403).send('Unauthorized');
return;
}
}
In my axios request I'm doing this:
const headerAPI = {
withCredentials: true,
Authorization: `Bearer ${myToken}`
}
allInfo = await axios.post('http://localhost:5001/stormtestfordota/europe-west1/api/hello', headerAPI);
But even if I put the correct auth token I receive this in the console
{"severity":"INFO","message":"Check if request is authorized with Firebase ID token"}
{"severity":"ERROR","message":"No Firebase ID token was passed as a Bearer token in the Authorization header. Make sure you authorize your request by providing the following HTTP header: Authorization: Bearer or by passing a "__session" cookie."}
And in my browser I get this error:
Access to XMLHttpRequest at 'http://localhost:5001/stormtestfordota/europe-west1/api/hello' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.
Even if I enabled CORS policies for localhost:3000.
Have you any idea why this is happening?
It was a problem with my CORS in my backend. I had to setup a whitelist and add the ip address of my frontend.
I'm try to pass the 'token_mailchimp' from axios get request to nodejs request get
For the moment i pass the auth token from a variable directly in app.js in my node/express project.
app.js in node/express project
app.get('/mailchimp/campaigns', checkAuth, function (req, res) {
request
.get('https://' + mailchimpInstance + '.api.mailchimp.com/3.0/campaigns')
.set('Content-Type', 'application/json;charset=utf-8')
.set('Authorization', 'Basic '+token_mailchimp)
.end((err, result) => {
if (err) {
res.status(500).json(err);
} else {
res.json(result.body);
}
});
});
axios get request in ReactJS project
.get('http://localhost:8081/mailchimp/campaigns',
{ headers: {"Authorization" : `Bearer `+jwt_token} })
.then(({ data })=> {
this.setState({
campaigns: data.campaigns
});
})
.catch((err)=> {})
How can i pass from axios request the auth token for the request /mailchimp/campaigns?
You can send a new custom header like x-api-token
{ headers: {"Authorization" : Bearer+jwt_token, "x-api-token" : "your_token"} }
Then in the app.js, access the headers from the request,
const {headers} = req;
Then use that in your API request
.set('Authorization',`Basic ${headers["x-api-token"]}`)
Note: If you are using cors plugin then make sure it's allowing that header to pass.
You can add header x-api-token manually in cors configuration if needed.
I have tried everything and can't get Axios to work with SAP Odata Post services. The problem is CSRF token validation failing but its working fine in Postman.
My request looks like this:
const postNewTasks = async (body, headers) => (await axios.get(getHeadersandCFRSURL, {
headers: { 'authorization': auth, 'x-csrf-token': 'fetch' },
withCredentials: true
}).then((response) => {
axios({
method: 'POST',
url: postBatchOperationsURL,
headers: {
"Authorization": auth,
"Content-Type": "multipart/mixed; boundary=batch_1",
"X-CSRF-Token": response.headers["x-csrf-token"], // set CSRF Token for post or update
},
withCredentials: true,
body: body
}).then(function (response) {
console.log(response)
return response
}).catch(function (err) {
console.log(err)
return err
})
})
)
Anybody has idea why the CSRF token validation fails with this axios request?
I had this issue recently and a solution that worked for me was to add a Cookie header with the cookies from the initial response set-cookie headers.
Postman does this automatically, but axios doesn't it would seem. My code from that part after "x-csrf-token":"fetch":
var xcsrftoken = response.headers["x-csrf-token"];
var cookies = '"';
for (var i = 0; i < response.headers["set-cookie"].length; i++) {
cookies += response.headers["set-cookie"][i] + ";";
}
cookies += '"';
axiosClient.defaults.headers.common[this.xcsrftokenName] = xcsrftoken;
axiosClient.defaults.headers.common["Cookie"] = cookies;
axiosClient is the object made from axios.create. I've set those headers as default so that I don't need to include them later in the requests. There were multiple set-cookie headers as well and it was necessary to combine them into one.
Trying to develop my API on NodeJS, I get my sign token and send it back on secure api routes, but the jwt is never valid even if it's the same token I generated! What is wrong in my code ?
I did my sign that way
pbkdf2(queryPassword, salt, 10000, length, digest, (err: Error, hash: Buffer) => {
if (hash.toString('hex') === userPassword) {
sign({'user': username, permissions: []}, secret, {expiresIn: '7d'}, (err, token => {
response.json({'token': token});
}));
} else {
response.json({'error': 'User / Password Mismatch'});
}
});
Here is the verify:
verify(token, secret, function(tokenError, decoded) {
if (tokenError) { // i'm always getting error...
return response.status(403).json({
message: 'Invalid token, please Log in first'
});
}
next();
});
here is my Angular2 service that request data from my API
let headers = new Headers({'Authorization': 'Bearer ' + this.token});
let options = new RequestOptions({headers: headers});
this.http.get(apiUrl, options);
token generated by sign:
eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyIjoidHQiLCJwZXJtaXNzaW9ucyI6W10sImlhdCI6MTQ4MzExNTAzNCwiZXhwIjoxNDgzNzE5ODM0fQ.bJbH4619JAU8pf_6qcYl0V1V5PxWsPBRYeXbeb6VL_M
token received by http service:
Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyIjoidHQiLCJwZXJtaXNzaW9ucyI6W10sImlhdCI6MTQ4MzExNTAzNCwiZXhwIjoxNDgzNzE5ODM0fQ.bJbH4619JAU8pf_6qcYl0V1V5PxWsPBRYeXbeb6VL_M
I finally found my error....
In my angular2 Api i was using this line
let headers = new Headers({'Authorization': 'Bearer ' + this.token});
i need to send only
let headers = new Headers({'Authorization': this.token});
the 'Bearer ' was causing me the error...