Cannot view authorization header - node.js

I'm using node.js default HTTP module and have an HTTP webserver.
I use request.headers to get all headers, but when I try to do request.headers.authorization it returns undefined, but there IS authorization as you can see here.
I tried to do JSON.parse(request.headers).authorization, still undefined, and crashes the process. How can I get the authorization header content?

Maybe you could use the method request.getHeader(name)
I looked in https://nodejs.org/api/http.html#http_request_getheader_name
Edit 1:
index.js
const http = require('http');
const server = http.createServer((request, response) => {
console.log(request.headers);
console.log(request.headers.authorization);
console.log('----');
const headers = {
'Content-Type': 'text/plain',
};
let statusCode = 404;
response.writeHead(200, headers);
response.end('Hi');
});
server.listen(8080, () => {
console.log(`Server listening on port :8080 🚀`);
});
Executing in terminal one:
node index.js
Terminal two:
curl localhost:8080 -H 'authorization: hello'
The output in terminal one is:
{ host: 'localhost:8080',
'user-agent': 'curl/7.68.0',
accept: '*/*',
authorization: 'hello' }
hello
----

Related

Forwarding FormData() request from NodeJS to another service

I am trying to forward my request from my NodeJS Proxy server to another server. The request I am trying to forward contains FormData()
I created FormData as per MDN docs
const payload = new FormData();
payload.append('addresses', file); // <---- UPLOADED FILE
payload.append('reason', 'reason');
payload.append('type', 'type');
This is how I am essentially sending the request to my NodeJS server
fetch("localhost:3000/v1/addresses", {
method: 'PUT',
body: payload
});
NodeJS Server at localhost:3000
const multer = require('multer');
const upload = multer();
app.put('/v1/addresses', upload.single('addresses'), (req, res) => {
let options = {
host: 'localhost',
method: 'PUT',
port: 8000,
path: req.originalUrl,
headers: req.headers,
formData: {
reason: req.body.reason,
type: req.body.type,
}
};
console.log("reason", req.body.reason) // "reason"
console.log("type", req.body.type) // "type"
console.log("addresses", req.file) // FILE OBJECT
const request = http.request(options, response => {
res.writeHead(response.statusCode, response.headers);
response.pipe(res);
});
request.end();
})
The code above, I'm not sure how to send over the actual file to the other service. Also, I am NOT seeing the reason and and type that I've passed over to the service.
What's also strange is that I see this in the incoming request in my NON- PROXY server
PUT /v1/addresses HTTP/1.1
Host: localhost:3000
Connection: keep-alive
Content-Length: 932
Sec-Ch-Ua: "Google Chrome";v="89", "Chromium";v="89", ";Not A Brand";v="99"
Sec-Ch-Ua-Mobile: ?0
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 11_2_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.90 Safari/537.36
Content-Type: multipart/form-data; boundary=----WebKitFormBoundaryt2p0AWOqJCnz95hg
Accept: */*
Origin: http://localhost:3000
Sec-Fetch-Site: same-origin
Sec-Fetch-Mode: cors
Sec-Fetch-Dest: empty
Referer: http://localhost:3000/blocklist
Accept-Encoding: gzip, deflate, br
Accept-Language: en-US,en;q=0.9
[object Object]
So after lots of searching and experimenting, this post actually provided me with the answer
Here is the code from the post.
const express = require("express");
const app = express();
const bodyParser = require('body-parser');
var multer = require('multer')();
const FormData = require('form-data');
const axios = require('axios');
const fs = require('fs');
app.use(bodyParser.json());
app.post('/fileUpload' , multer.single('fileFieldName'), (req , res) => {
const fileRecievedFromClient = req.file; //File Object sent in 'fileFieldName' field in multipart/form-data
console.log(req.file)
let form = new FormData();
form.append('fileFieldName', fileRecievedFromClient.buffer, fileRecievedFromClient.originalname);
axios.post('http://server2url/fileUploadToServer2', form, {
headers: {
'Content-Type': `multipart/form-data; boundary=${form._boundary}`
}
}).then((responseFromServer2) => {
res.send("SUCCESS")
}).catch((err) => {
res.send("ERROR")
})
})
const server = app.listen(3000, function () {
console.log('Server listening on port 3000');
});

NodeJS send http request with absoluteURI

I'm working with a weird HTTP server that only accepts HTTP request which looks like:
GET http://10.0.0.1/test
Host: 10.0.0.1
Cache-Control: no cache
Connection: Keep-Alive
Node the "http://" at the path
When I'm sending HTTP request (using the code at the bottom) the request looks like:
GET /test
Host: 10.0.0.1
Cache-Control: no cache
Connection: Keep-Alive
Code example:
var request = require('request');
var options = {
'method': 'GET',
'uri': 'http://10.0.0.1/test',
'headers': {
'Host': '10.0.0,1',
'Cache-Control': 'no cache',
'Connection': 'Keep-Alive'
}
};
request(options, function (error, response) {
if (error) throw new Error(error);
console.log(response.body);
});
Any idea how I can send the request like the server expects using standard libaries?

nodejs cannot perform http post with autorization header

this is the request i want to perform:
POST /v1/oauth2/token HTTP/1.1
Host: api.sandbox.paypal.com
Accept: application/json
Accept-Language: en_US
Authorization: Basic cGF5cGFsaWQ6c2VjcmV0
Content-Type: application/x-www-form-urlencoded
grant_type=client_credentials
I tried it in nodejs using this code:
paypalSignIn = function(){
var username = process.env.PAYPALID;
var password = process.env.PAYPALSECRET;
var auth = 'Basic ' + Buffer.from(username + ':' + password).toString('base64');
// new Buffer() is deprecated from v6
// auth is: 'Basic VGVzdDoxMjM='
var post_data = querystring.stringify({
'grant_type' : 'client_credentials',
});
var header = {'Accept': 'application/json', 'Authorization': auth, 'Accept-Language': 'en_US'};
const options = {
hostname: 'api.sandbox.paypal.com',
port: 443,
path: '/v1/oauth2/token',
method: 'POST',
headers: header,
}
var post_req = http.request(options, function(res) {
res.setEncoding('utf8');
res.on('data', function (chunk) {
console.log('Response: ' + chunk);
});
});
post_req.write(post_data);
post_req.end();
}
Unfortunately i'm getting the following error:
Error: socket hang up
Try using the https module (it's not enough to set port 443, you have to use the HTTPS protocol to connect to an HTTPS endpoint).
I also noticed you didn't set the Content-Type header. It depends on the API, but that may cause problems for you too.
Finally, I'd consider using a library that wraps http/https like node-fetch, bent, or axios for this rather than the standard library directly. It can handle things like writing to the socket, setting the Content-Length header, etc.

How To Get HTTP Authorization header With Express and Apollo-Server

I can not access the "Authorization" header in each HTTP request on my Apollo-Server, implemented with express.
Here is my setup of express, Apollo-Server, CORS, etc.
const corsConfig = {
credentials: true,
allowedHeaders: ['Authorization'],
exposedHeaders: ['Authorization']
};
const app = express()
const server = new ApolloServer({
schema,
context: ({ req }) => {
return {
req
};
}
});
server.applyMiddleware({
app,
path,
cors: corsConfig
});
http.createServer(app).listen(port, () => logger.info(`Service started on port ${port}`));
And inside my resolvers, I bring in the context, particularly the req object (this is an example graphQL endpoint resolver):
const exampleQuery = async (parent, input , { req }) => {
console.log(req.headers);
/*
The output of this log:
{
'content-type': 'application/json',
accept: '*/*',
'content-length': '59',
'user-agent': 'node-fetch/1.0 (+https://github.com/bitinn/node-fetch)',
'accept-encoding': 'gzip,deflate',
connection: 'close',
host: 'localhost:3301',
'Access-Control-Allow-Headers': 'Authorization',
'Access-Control-Expose-Headers': 'Authorization'
}
*/
}
I have sent requests to this endpoint, with an "Authorization" header, containing a token as the value. However, the Authorization header is not in the req.headers object (in fact, it's not in the entire req object either). I am certain that my Postman/Insomnia HTTP requests to this endpoint are sending out the Authorization header, however it seems to be not getting through my Apollo-Server.
Anyone have any insight as to why the Authorization header is not going through?
SOLUTION:
The problem was actually that I am using an Apollo federated microservices architecture, which requires additional configuration on the gateway to pass the Authorization header onto the individual microservices, where the resolvers are. You have to add the buildService function inside the ApolloGateway constructor, where you specify that a RemoteGraphQLDataSource willSendRequest of context.req.headers.authentication to the underlying microservices
It works as expected, E.g.
server.ts:
import { ApolloServer, gql, makeExecutableSchema } from 'apollo-server-express';
import express from 'express';
import http from 'http';
const corsConfig = {
credentials: true,
allowedHeaders: ['Authorization'],
exposedHeaders: ['Authorization'],
};
const typeDefs = gql`
type Query {
hello: String
}
`;
const resolvers = {
Query: {
hello: (_, __, { req }) => {
console.log(req.headers);
return 'world';
},
},
};
const schema = makeExecutableSchema({ typeDefs, resolvers });
const app = express();
const path = '/graphql';
const port = 3000;
const server = new ApolloServer({
schema,
context: ({ req }) => {
return {
req,
};
},
});
server.applyMiddleware({ app, path, cors: corsConfig });
http.createServer(app).listen(port, () => console.info(`Service started on port ${port}`));
Send a GraphQL query HTTP request via curl:
curl -X POST -H "Content-Type: application/json" -H "Authorization: Bearer abc123" --data '{ "query": "{ hello }" }' http://localhost:3000/graphql
{"data":{"hello":"world"}}
Server-side logs:
Service started on port 3000
{ host: 'localhost:3000',
'user-agent': 'curl/7.54.0',
accept: '*/*',
'content-type': 'application/json',
authorization: 'Bearer abc123',
'content-length': '24' }

ERR_INVALID_HTTP_RESPONSE on nodejs http2

When using node new http2 server, I encountered this error when attempting to call it from the browser: ERR_INVALID_HTTP_RESPONSE.
The code:
const http2 = require('http2');
// Create a plain-text HTTP/2 server
const server = http2.createServer();
server.on('stream', (stream, headers) => {
console.log('headers: ', headers);
stream.respond({
'content-type': 'text/html',
':status': 200
});
stream.end('<h1>Hello World</h1>');
});
server.listen(80);
Turns out, chrome won't allow you to access insecure http2 servers, I had to change the code to:
const server = http2.createSecureServer({
key,
cert
});
and then it worked.

Resources