How to Add Two-Factor Authentication with Swift and Vapor

Introduction

Two-factor authentication (2FA) is when you use two different things to verify your identity. Usually, something you know, like a password, paired with a verification code from a physical device like a phone.

Prerequisites

  • Xcode 12 and Swift 5 or greater.
  • Vapor 4.0 installed on your machine.
  • ngrok for exposing your local machine to the internet.

Vonage API Account

To complete this tutorial, you will need a Vonage API account. If you don’t have one already, you can sign up today and start building with free credit. Once you have an account, you can find your API Key and API Secret at the top of the Vonage API Dashboard.

Create a Vapor Project

You can create a Vapor project using the new project command vapor new SwiftVerify -n in your terminal. Once the command has finished change directory into the folder, it created for you using cd SwiftVerify. Now you can open the project in Xcode using vapor xcode.

Create the Model Structs

A major benefit of using Vapor is that you can lean on the Swift language’s type-safety. You can model inputs and outputs to your server using structs that conform to the Codable protocol; Vapor has a protocol called Content for this.

Create a Verification Request

You need to make a call to the Verify API to create a verification request. The endpoint you want to call to create a verification request is /verify. Create a function in the Vonage struct to do so:

Check the Code

Checking if the code is valid is a very similar process. Add a function to the Vonage struct to call the Verify API, this time making a post request to /verify/check with a CheckVerificationBody struct:

Test Your Server

Now that your routes are defined, you can build and run (CMD + R) your server. Once complete, your server will be running locally on port 8080.

Developer content from the team at Vonage, including posts on our Java, Node.js, Python, DotNet, Ruby and Go SDKs