Keyboard Interactive Authentication

In Working with the Client API we briefly covered how to authenticate the client. To authenticate we place a set of Authenticator implementations on the SshContext. The client iterates over these attempting each authentication in turn until the server notifies it that the connection has been authenticated.

The first task is to tell the client the remote username for this connection.

    sshContext.setUsername("lee");	

The keyboard interactive authentication mechanism implements SSH challenge response authentication. In many server implementations this simply provides a standard password prompt. But it can be used by servers to provide other types of authentication that require variable prompts. 

If you are connecting to a server that requires password over keyboard interactive then you can use the basic password authenticator. The API will detect this and create a default KeyboardInteractiveAuthenticator instance to handle the over keyboard-interactive case.

    sshContext.addAuthenticator(new PasswordAuthenticator("xxxxxxx"));

Its also possible to use the KeyboardInteractiveAuthenticator directly however doing this would also require you use the Password Authenticator too since it will not be automatically handled by the API.

    sshContext.addAuthenticator(
new KeyboardInteractiveAuthenticator( new PasswordOverKeyboardInteractiveCallback(
new PasswordAuthenticator("xxxxxxx"))));

 

Custom Implementation

If the server you are connecting to provides a custom keyboard-interactive authentication with multiple or several rounds of prompts you can implement your own callback interface. We have provided an AbstractKeyboardInteractiveCallback that simplifies this so that you just have to implement a single method to show the prompts to the user.

The following example shows the user being prompted through the console. 

    sshContext.addAuthenticator(
	new KeyboardInteractiveAuthenticator(
		new AbstractKeyboardInteractiveCallback() {
	    @Override
	    public void showPrompts(String name, 
				    String instruction, 
				    KeyboardInteractivePrompt[] prompts,
				    KeyboardInteractivePromptCompletor completor) {	
		try {
		    BufferedReader reader = new BufferedReader(
			    new InputStreamReader(System.in));
		    System.out.println(instruction);
		    for(KeyboardInteractivePrompt prompt : prompts) {
			System.out.print(prompt.getPrompt());
			prompt.setResponse(reader.readLine());
		    }
		    completor.complete();
		} catch (IOException e) {
		    completor.cancel();
	        }
	    }		
    }));

 

Note that showPrompts is called asynchronously so in order to finish the operation you need to call the complete method on the KeyboardInteractivePromptCompletor object. If the user does not want to complete authentication call the cancel method.

 

 

 

 

Have more questions? Submit a request

0 Comments

Please sign in to leave a comment.