Two-factor authentication with Appium

Use Perfecto APIs to access third-party applications on your mobile device.

Two-factor authentication is a great way to allow your users protect themselves against getting their accounts hacked.

When the users want to authenticate, they will use their personal access license – such as user name and password, plus a one-time-valid, dynamic passcode consisting of digits.

The code is sent to their mobile device by SMS or via a special app.

How do I implement this flow in my Appium script?

Lets have a look at the example of Salesforce two-factor authentication login flow below.

As you can imagine, the challenging part will be the retrieval of the authentication code from the SMS application. It gets tricky after this step.

Just received the login verification code via SMS

Just received the login verification code via SMS

The standard Appium APIs do not allow you to access third-party applications. We will be using the Perfecto APIs to implement this set of steps.

  1. Launch the SMS application.

  2. Retrieve the “code”.

  3. Launch the Salesforce1 application.

  4. Enter the retrieved “code” for verification.

Copy
Map<String, String> startapp = new HashMap<>();
startapp.put("name", "Messages");
Object result = driver.executeScript("mobile:application:open", startapp);

String command = "mobile:edit-text:get";
Map<String, String> gettext = new HashMap<>();
gettext.put("label", "Use");
gettext.put("label.direction", "left");
gettext.put("timeout", 60);
String code = (String)driver.executeScript(command, gettext);

startapp.put("name", "Salesforce1");
driver.executeScript("mobile:application:open", startapp);

driver.findElementByXPath("//*[@name=\"Verification Code\"][2]").sendKeys(code);

Two- factor authentication is one of dozens of flows that require accessing a third party application on the device. You can utilize the Perfecto OS level control, to implement any one of these flows - whether it's an incoming call flow, switching context to the Facebook app or test the background - foreground scenario of your application.