Set Express response headers before redirect - node.js

I'm implementing a site login that takes in an email/password combo, retrieves an API token, and returns it to the user to get stored (encrypted) in localStorage.
Currently, on successful POSTing to /login, the app redirects the user to the index page, with the token attached as a query, like so (as suggested here):
login.post('/', function(req, res) {
...checking password...
Auth.getToken(user, function(err, token) {
res.redirect('/?token=' + token);
});
});
This works fine, but I'd prefer to keep my URLs as clean as possible and set the token as a header instead:
login.post('/', function(req, res) {
...checking password...
Auth.getToken(user, function(err, token) {
res.set('x-access-token', token);
console.log(res._headers);
// --> {'x-powered-by': 'Express', 'x-access-token': <token>}
res.redirect('/');
});
});
console.log-ing res._headers shows that the headers are set as expected, but when I log req.headers on the request to the index page, it's not showing up:
{ host: 'localhost:3000',
connection: 'keep-alive',
'cache-control': 'max-age=0',
accept: 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
'upgrade-insecure-requests': '1',
'user-agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/44.0.2403.157 Safari/537.36',
referer: 'http://localhost:3000/login',
'accept-encoding': 'gzip, deflate, sdch',
'accept-language': 'en-US,en;q=0.8',
cookie: 'ifusr=crwj; _ga=GA1.1.1933420201.1409901705',
'if-none-match': '"1195161647"' }
Any suggestions appreciated!

Setting headers wouldn't work here because a redirect will execute a new http request, you can use express-session to store the auth token and fetch it when you need it
req.session.accessToken = token

Related

Connecting to api using basic auth Angular 8 Express js

I have set up an angular 8 app, that connects to an express API.
I'm running it locally, to test.
My front end app connects to http://localhost:4200/ and backend to http://localhost:3000/
I've set up an express route to connect to https://api.podbean.com/v1/podcasts?access_token=baee9cb65384a814e704adc626dc969bb019f84d
which works fine, returning all podcasts
But the debugToken endpoint never works via the express route, if I use https://api.podbean.com/v1/oauth/debugToken?access_token=baee9cb65384a814e704adc626dc969bb019f84d
Using postman with basic auth clientId = '7faf9a7ad38a01c7d900c' client_secret = 'a7a3825f02be39c57ff44' it works ok, but never when connecting via localhost
I'm using GET
It must be connecting because I get an object returned, although it's an error
In Angular:
debug() {
const httpOptions = {
headers: new HttpHeaders({
'Content-Type': 'application/json',
Authorization: 'Basic ' + btoa('7faf9a7ad38a01c7d900c:a7a3825f02be39c57ff44')
})
};
console.log(httpOptions);
return this.http.get(`${this.configUrl}/debug/`, httpOptions);
}
Express:
router.get('/debug', function (req, res, next) {
var options = {
url: `https://api.podbean.com/v1/oauth/debugToken?access_token=${accessToken}`
}
request(options, function (err, response, body) {
console.log( req.headers);
if(err){
return res.status(500).json({
title: 'An error has occured',
error: err
})
}
res.json(JSON.parse(body));
next();
})
});
When I log the request headers in the express/node side
{host: 'localhost:3000',
connection: 'keep-alive',
pragma: 'no-cache',
'cache-control': 'no-cache',
'sec-fetch-mode': 'cors',
origin: 'http://localhost:4200',
authorization: 'Basic N2ZhZjlhN2FkMzhhMDFjN2Q5MDBjOmE3YTM4MjVmMDJiZTM5YzU3ZmY0NA==',
'content-type': 'application/json',
accept: 'application/json, text/plain, */*',
'user-agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.132 Safari/537.36',
dnt: '1',
'sec-fetch-site': 'same-site',
referer: 'http://localhost:4200/',
'accept-encoding': 'gzip, deflate, br',
'accept-language': 'en-GB,en;q=0.9,en-US;q=0.8,it;q=0.7,es;q=0.6' }
Returned object:
{"error":"invalid_token","error_description":""}
Which tells me I'm connecting, just not correctly
Looks like you just confused endpoints. You are sending basic auth from Angular page to your Express endpoint,
which doesn't make much sense, because it's https://api.podbean.com who requires authorization, not your Express server.
Try adding basic auth credentials to the request which goes from your Express server to api.podbean.com
router.get('/debug', function (req, res, next) {
var options = {
url: `https://api.podbean.com/v1/oauth/debugToken?access_token=${accessToken}`,
headers: {
'Authorization': 'Basic ' + new Buffer("7faf9a7ad38a01c7d900c:a7a3825f02be39c57ff44").toString('base64')
}
}
request(options, function (err, response, body) {
...

Missing authentication field in headers to store cookie expressjs

I'm trying to login with cookie JWT HTTPOnly, the problem is that the cookie comming with the response to the server, is comming in a field named 'cookie' and I would liked to have the cookie in a field named 'authorization' with a type 'Bearer' token. I'm using axios as client...
This is how the headers coming from my browser looks like...
{ host: 'localhost:8000',
connection: 'keep-alive',
accept: 'application/json, text/plain, */*',
origin: 'http://localhost:8080',
'user-agent':
'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.169 Safari/537.36',
referer: 'http://localhost:8080/allusers',
'accept-encoding': 'gzip, deflate, br',
'accept-language': 'pt-PT,pt;q=0.9,en-US;q=0.8,en;q=0.7',
cookie:
'jwt=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6IjVkNzE2ODI4NjE4ZjllMTQzYzY2NjIwNSIsImlhdCI6MTU2ODEwNzkxMSwiZXhwIjoxNTcwNjk5OTExfQ.cq85nqtLlw4npP53_3x-YxhXvapsm9qXKgOH0RCkLIM' }
this is how a send my cookie JWT
const token = jwt.sign({
id: user._id
},
process.env.JWT_SECRET, {
expiresIn: process.env.JWT_EXPIRES_IN
}
);
const cookieOptions = {
expires: new Date(
Date.now() + process.env.JWT_COOKIE_EXPIRES_IN * 24 * 60 *
60 * 1000
),
httpOnly: true
};
res.cookie('jwt', token, cookieOptions);
Instead of doing res.cookie('jwt', token, cookieOptions);
You could try using the standard response header.
You can set a header field to a value of your choosing:
res.set('Content-Type', 'text/plain');
Or set your own:
res.set(field, [value]);
I hope this helps!
Also maybe let the server make JWT keys in the future. That is how most people do it.
A good read is: The Hard Parts of JWT Security Nobody Talks About

Node server unable to retrive the value of react axios request header parameter

I need to access axios header authorization token in server side(Node), showing undefined. Please help..
Client side(React) request:
var config = {
headers: {
'cache-control':'no-cache',
'content-type': 'application/x-www-form-urlencoded',
'authorization' :'bearer '+Auth.getToken()
}
};
axios.get(ApiConfig.API_BASE+'api/admin/profile/', config).then(function(response) {
this.setState({status:'success', profile: response.data.data});
}).catch(function(response) {
console.log(response);
});
Server side(Node):
module.exports = (req, res, next) => {
console.log(req.headers.authorization);
if(!req.headers.authorization) {
return res.status(401).end();
}
};
Log showing undefined. I also console the entire header, but their output is:
{ host: 'localhost:8027',
'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:55.0) Gecko/20100101 Firefox/55.0',
accept: 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
'accept-language': 'en-US,en;q=0.5',
'accept-encoding': 'gzip, deflate',
'access-control-request-method': 'GET',
'access-control-request-headers': 'authorization,cache-control',
origin: 'http://localhost:3001',
connection: 'keep-alive' }
How do I retrieve the authorization token value?
Thank you.
I'm assuming you are using express. If so, instead of getting the header value as req.headers.authorization, try req.get('authorization').
http://expressjs.com/en/api.html#req.get
If you are making a cross-origin HTTP request, please make sure CORS has been enabled in your server. If you are using express cors middleware can be used.
I guess your problem here is that since CORS has not been enabled, your server will receive a OPTIONS request first, so the entire header you console is from the OPTIONS request not the GET request as you desired. You can use console.log(req.method) to verify. BTW req.headers.authorization is ok to receive the header.

NodeJs request.get() function not working while the url is accessible from the browser

I am using the request npm module.I want to retrieve an image from a url. The request.get(url) function is returning me a '400 Bad Request', whereas the image is accessible from the browser.
The url i am hitting is : http://indiatribune.com/wp-content/uploads/2017/09/health.jpg
You could try to add some headers:
const request = require('request');
request.get({
url: 'http://indiatribune.com/wp-content/uploads/2017/09/health.jpg',
headers: {
Accept: 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8',
'Accept-Encoding': 'gzip, deflate',
'Accept-Language': 'en-GB,en;q=0.8,en-US;q=0.6,hu;q=0.4',
'Cache-Control': 'max-age=0',
Connection: 'keep-alive',
Host: 'indiatribune.com',
'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.113 Safari/537.36',
},
}, (err, response, data) => {
console.log(response, data);
});
The User-Agent seems to be enough.
Use download module . It's pretty simple.
const fs = require('fs');
const download = require('download');
download('http://indiatribune.com/wp-content/uploads/2017/09/health.jpg').pipe(fs.createWriteStream('foo.jpg'));

Aurelia http-client/http-fetch not sending headers

Tried multiple approaches to send custom-headers via Aurelia-http-client and Aurelia-Fetch-client to pass Headers in the get/post requests that I am making, but in the actual request, the headers are not being passed
approach 1
var client = new HttpClient()
client.createRequest('/api/information/save')
.asPost()
.withBaseUrl('http://10.0.0.13:3000')
.withHeader("X-auth-code", "abc")
.send()
approach 2
var client = new HttpClient()
.configure(x => {
x.withBaseUrl('http://10.0.0.13:3000');
x.withCredentials(true);
x.withHeader('Content-Type', 'application/json; charset=utf-8');
x.withHeader('x-client-code', 'abc');
});
Approach 3
this.http.configure(config => {
config
.withDefaults({
credentials: 'same-origin',
headers: {
"Content-Type": "application/json",
"x-client-code": "abc",
}
})
.useStandardConfiguration()
.withInterceptor({
request(request) {
request.headers.append("x-client-code","abc");
console.log(`${request.headers}`);
return request; // you can return a modified Request, or you can short-circuit the request by returning a Response
},
response(response) {
console.log(`Received ${response.status} ${response.url}`);
return response; // you can return a modified Response
}
});
})
But all of them lead to the same error
{ host: '10.0.0.13:3000',
connection: 'keep-alive',
'access-control-request-method': 'POST',
origin: 'http://localhost:9000',
'user-agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.104 Safari/537.36',
'access-control-request-headers': 'content-type',
accept: '*/*',
referer: 'http://localhost:9000/',
'accept-encoding': 'gzip, deflate',
'accept-language': 'en-GB,en-US;q=0.8,en;q=0.6' }
At the end we are unbable to pass the headers.
it's a security against cross-site scripting (and it's super annoying) #see : Cors Access-Control-Allow-Headers wildcard being ignored?

Resources