node.jssspifastifynode-sspi

how to use node-sspi with fastify


I want to use https://github.com/abbr/nodesspi

I am trying to use justify instead of express. It looks like it should just work but it doesn't. Its pretty much the equivalent of the express snippet. I get an error at the authenticate function telling me I pass a wrong argument.

const fastify = require('fastify')({
  logger: true,
})

fastify.route({
  method: 'GET',
  url: '/login',
  onRequest: function (req, res, next) {
    var nodeSSPI = require('node-sspi')
    var nodeSSPIObj = new nodeSSPI({
      retrieveGroups: true
    })
    nodeSSPIObj.authenticate(req, res, function (err) {
      res.finished || next()
    })
  },
  handler: function (req, res, next) {
    var out =
      'Hello ' +
      req.connection.user +
      '! Your sid is ' +
      req.connection.userSid +
      ' and you belong to following groups:<br/><ul>'
    if (req.connection.userGroups) {
      for (var i in req.connection.userGroups) {
        out += '<li>' + req.connection.userGroups[i] + '</li><br/>\n'
      }
    }
    out += '</ul>'
    res.send(out)
  }
})

fastify.listen(4000, err => {
  if (err) throw err
})

"fastify": "^3.3.0", "node-sspi": "^0.2.8",


Solution

  • The issue is that express like middle ware doesnt work on the fastify instance. The solution involves fastify-express

    const fastify = require('fastify')({ logger: true })
    
    fastify.register(async (fastify) => {
      await fastify.register(require('fastify-express'))
      const nodeSSPI = require('node-sspi')
      const nodeSSPIObj = new nodeSSPI()
    
      fastify.use((req, reply, done) => {
        nodeSSPIObj.authenticate(req, reply, (err) => {
          if (err) return reply.code(500).send({ error: err })
          reply.finished || done()
        })
      })
    
      fastify.get('/', (req, reply) => {
        const { userSid, user, userGroups } = req.connection
        return reply.send({ userSid, user, userGroups })
      })
    })
    
    fastify.listen(3000, (err) => {
      if (err) throw err
    })