user1609085
user1609085

Reputation: 885

Authenticate jwt token and proxy to another server using Node JS

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.

Upvotes: 1

Views: 1731

Answers (1)

user1609085
user1609085

Reputation: 885

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)

Upvotes: 2

Related Questions