1

Want to use NodeJS as reverse proxy to another server.

My Scenario is to authenticate all requests (each request will have jwt token), authentication using jwt in nodejs is fine.

Same request should be sent to another server after successful authentication and the response should be sent back to client.

Looked into redbird, node-http-proxy and other readily available nodejs proxy modules. Nothing have a concrete way of authenticating the jwt and redirecting to target.

Is there a module which can be used? If not any idea/what steps I can follow to achieve this? Also I will be adding tls termination.

2
  • You can try NGNIX Proxy server. Commented Jul 2, 2018 at 6:34
  • I want to use Node as proxy server Commented Jul 2, 2018 at 15:03

1 Answer 1

2

I was able to get something to work this might not be an optimal solution. This is an http proxy server. Next quest is to modify this to use as https server with tls termination (which is not the scope for this question atleast)

let http = require('http')
let httpProxy = require('http-proxy')

let jwt = require('jsonwebtoken')
let token = require('./token.json')

let proxy = httpProxy.createProxyServer({})

let server = http.createServer(function(req, res) {
  jwt.verify(req.headers["authorization"], token.secret, { issuer:'IssuerName' }, function(err, decoded) {
    if(err){
      console.log("Error: " + err)
      res.setHeader('Content-Type','application/json')
      res.write(JSON.stringify({"statusCode":401, "message":err}))
      res.end()
      return
    }
    proxy.web(req, res, {
      changeOrigin: true,
      target: 'https://some_url'
    })
  })
})

proxy.on('proxyReq', function(proxyReq, req, res, options) {
  proxyReq.removeHeader('authorization')
})

proxy.on('error', function (err, req, res) {
  res.setHeader('Content-Type','application/json')
  res.write(JSON.stringify({"statusCode":500, "message":err}))
  res.end()
})

let port = process.env.PORT || 9200
server.listen(port)
console.log('HTTP Proxy server is running on port: ' + port)
Sign up to request clarification or add additional context in comments.

1 Comment

Hi there! Did you ever find a better solution? I would love to find a standalone express package or library that can do that ... Nodejs or something else, it doesn't really matter to me.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.