Java Requires Chilkat v11.0.0+
Chilkat2 Java
SFTP Auth Failure Reason (AuthenticatePwPk)
See more SFTP Examples
This example demonstrates how to determine the failure reason for the case where both a password and private key are required for authentication. If authentication fails, was it because of an invalid private key, or an invalid password?Chilkat Java Downloads
import com.chilkatsoft.chilkat2.ChilkatException;
import com.chilkatsoft.chilkat2.JsonObject;
import com.chilkatsoft.chilkat2.SFtp;
import com.chilkatsoft.chilkat2.SshKey;
public class ChilkatExample {
public static void main(String[] args) {
boolean success = false;
// This example assumes the Chilkat API to have been previously unlocked.
// See Global Unlock Sample for sample code.
// Load a private key to be used for SSH authentication.
SshKey key = new SshKey();
key.setPassword("key_password");
try {
key.fromOpenSshPrivateKey(key.loadText("qa_data/my_private_key_file"));
} catch (ChilkatException e) {
System.out.println(e.getLastErrorText());
return;
}
SFtp sftp = new SFtp();
try {
sftp.connect("sftp.example.com", 22);
} catch (ChilkatException e) {
System.out.println(e.getLastErrorText());
return;
}
// Authenticate using both a password and private key.
try {
sftp.authenticatePwPk("myLogin", "myPassword", key);
success = true;
} catch (ChilkatException e) {
success = false;
}
if (success) {
System.out.println("Authentication is successful!");
return;
}
// If we get here, it means the authentication failed.
// Examine the last JSON data..
JsonObject json = new JsonObject();
sftp.getLastJsonData(json);
json.setEmitCompact(false);
// This is the JSON if the key is correct, but the password is incorrect:
// {
// "public_key_type": "rsa",
// "partialAuthResult": "publickey success. continue to authenticate with password...",
// "authResult": "failed",
// "authFailReason": "Password is incorrect"
// }
// This is the JSON if the key is incorrect. We won't know if the password is also incorrect until
// the key is made correct so that authentication proceeds to check the password.
// {
// "public_key_type": "rsa",
// "authResult": "failed",
// "authFailReason": "Key is incorrect"
// }
// To get the authResult anbd authFailReason:
System.out.println("authResult: " + json.stringOf("authResult"));
System.out.println("authFailReason: " + json.stringOf("authFailReason"));
}
}