What are some examples of "authHandler" in the "connect" client method of the ssh2 npm package?

511 Views Asked by At

What are some examples of "authHandler" in the "connect" client method of the ssh2 npm package?

im namely looking to re-order the methods and/or remove some.

2

There are 2 best solutions below

0
On BEST ANSWER

Using the documentation, I'm going to try and provide a basic example which include usage of authHandler as mentioned in your question.

// Require Client Class from ssh2
const { Client } = require('ssh2');

// Create instance of Client (aka connection)
const conn = new Client();

// Create our ready event that's called after we connect
conn.on('ready', () => {
    console.log('Client :: ready');
});

// Connect with a config object passed in the parameters
conn.connect({
    host: '192.168.100.100',
    port: 22, // SSH

    // Authentication Handler
    authHandler: function (methodsLeft, partialSuccess, callback) {

        // Code e.g. get credentials from database
    
        // Once your logic is complete invoke the callback
        // http://npmjs.com/package/ssh2#client-examples
        callback({
            type: 'password',
            username: 'foo',
            password: 'bar',
        });
    }
});

The above should provide a working example if the credentials are changed. The code can be made slightly cleaner and the calls for conn class can be chained like so:

conn.on('ready', () => {
    console.log('Client :: ready');
}).connect({ // Chained
    host: '192.168.100.100',
    port: 22, // SSH

    // Authentication Handler
    authHandler: function (methodsLeft, partialSuccess, callback) {

        // Code e.g. get credentials from database
    
        // Once your logic is complete invoke the callback
        // http://npmjs.com/package/ssh2#client-examples
        callback({
            type: 'password',
            username: 'foo',
            password: 'bar',
        });
    }
});
0
On

Thanks for this @Riddell! Just adding to that answer. Using this approach, I was still getting an error that said 'Invalid username'.

Thing is, even when using authHandler() and returning the credentials in the callback, you still need to mention the 'username' in the base config object as well like this:

conn.on('ready', () => {
    console.log('Client :: ready');
}).connect({
    host: '192.168.100.100',
    port: 22,
    username: 'foo',

    authHandler: function (methodsLeft, partialSuccess, callback) {
        callback({
            type: 'password',
            username: 'foo',
            password: 'bar',
        });
    }
});

Also, if anyone is getting an error with the Auth Type when using this approach, you need to upgrade your ssh2 package version. Faced this issue when using [email protected] and got it resolved after upgrading to [email protected]