> ## Documentation Index
> Fetch the complete documentation index at: https://plivo.com/docs/llms.txt
> Use this file to discover all available pages before exploring further.

# Two-Factor Authentication

> Set up SMS-based two-factor authentication with OTP using Plivo APIs

Two-factor authentication (2FA) can play a key role in securing your applications against password data breaches. Authentication with a one-time password (OTP) delivered to your users over SMS is an effective approach to implementing two-factor authentication. Plivo’s premium direct routes guarantee the highest possible delivery rates and the shortest possible delivery times for your 2FA SMS messages.

This guide shows how to set up SMS-based two-factor authentication using either {/* [PHLO](/phlo/getting-started/getting-started) */} or traditional API development. PHLO lets you create and deploy workflows from an intuitive graphical canvas in few clicks.

<Tabs>
  <Tab title="Using API">
    Here’s how to implement 2FA using Plivo APIs.

    <h2 id="xml-prerequisites">Prerequisites</h2>

    To get started, you need a Plivo account —  [sign up](https://cx.plivo.com/signup) with your work email address if you don’t have one already. If this is your first time using Plivo APIs, follow our instructions to [set up a Python development environment](/sdk/server/setting-up-dev-environment).

    <h2 id="xml-set-up-the-demo-application-locally">Set up the demo application locally</h2>

    * Clone the repository from [GitHub](https://github.com/plivo/2fa-python-demo).

    ```sh theme={null}
    $ git clone https://github.com/plivo-dev/2fa-python-demo
    ```

    * Change your working directory to 2fa-python-demo.

    ```sh theme={null}
    $ cd 2fa-python-demo
    ```

    * Install the dependencies using the requirements.txt file.

    ```sh theme={null}
    $ pip install -r requirements.txt
    ```

    * Edit config.py. Replace the auth placeholders with your authentication credentials from the [Plivo console](https://cx.plivo.com/home). Replace the phone number placeholder with an actual phone number in [E.164 format](https://en.wikipedia.org/wiki/E.164) (for example, +12025551234). Replace the PHLO ID with `null`.

    <Frame>
      <img src="https://mintcdn.com/plivo/-VVFcM3g7XHd8wTl/images/python-config.png?fit=max&auto=format&n=-VVFcM3g7XHd8wTl&q=85&s=e215d4bf78bf2785a8c8fc50598b52f2" alt="Configuration file" width="1440" height="900" data-path="images/python-config.png" />
    </Frame>

    <h2 id="xml-a-review-of-the-code">A review of the code</h2>

    Let‘s walk through what the code does.

    <h3 id="xml-generate-the-otp">Step 1:  Generate the OTP</h3>

    Use the Time-Based OTP algorithm to generate a random six-digit one-time password (OTP).

    ```py theme={null}
    def generate_code(self):
            code = random.choice(range(100000, 999999))  # generating 6-digit random code
            return code
    ```

    <h3 id="xml-send-sms-message-with-otp">Step 2: Send an SMS message with the OTP</h3>

    Send an SMS message with the OTP to the user’s registered mobile number using Plivo’s Send Message API.

    ```py theme={null}
    def send_verification_code_sms(self, dst_number: str, message):
            """
            `send_verification_code` accepts destination number
            to which the message that has to be sent.

            The message text should contain a `__code__` construct
            in the message text which will be
            replaced by the code generated before sending the SMS.
        
            :param: dst_number
            :param: message
            :return: verification code
            """
            try:
                response = self.client.messages.create(
                    src=self.app_number, dst=dst_number, text=message
                )
                print(response)
                return response
            except exceptions as e:
                print(e)
                return "Error encountered", 400
    ```

    <h3 id="xml-make-a-phone-call-with-otp">Failover: Make a phone call with the OTP</h3>

    If the SMS message doesn’t reach the mobile device, the user can request a voice OTP.

    ```py theme={null}
    def send_verification_code_voice(self, dst_number, code):
    try:
            response = self.client.calls.create(
                    from_=self.app_number,
                    to_=dst_number,
                    answer_url=f"https://twofa-answerurl.herokuapp.com/answer_url/{code}",
                    answer_method="GET",
                )
                return response
            except exceptions as e:
                print(e)
                return "Error encountered", 400
    ```

    <h3 id="xml-verify-the-otp">Step 3: Verify the OTP</h3>

    Verify the OTP the user entered on their handset.

    ```py theme={null}
    @app.route("/checkcode/<number>/<code>")
    def check_code(number, code):
        """
        check_code(number, code) accepts a number and the code entered by the user and
        tells if the code entered for that number is correct or not.
        """

        original_code = current_app.redis.get("number:%s:code" % number)
        if original_code == code:  # verification successful, delete the code
            current_app.redis.delete("number:%s:code" % number)
            return (jsonify({"status": "success", "message": "codes match, number verified"}),200,)
        elif original_code != code:
            return (
                jsonify(
                    {
                        "status": "rejected",
                        "message": "codes do not match, number not verified",
                    }
                ),
                404,
            )
        else:
            return (jsonify({"status": "failed", "message": "number not found"}), 500)
    ```

    <h2 id="xml-test">Test</h2>

    To test the application, start the Redis server.

    ```sh theme={null}
    $ redis-server
    ```

    Save your code and run it.

    ```shell theme={null}
    $ flask run
    ```

    <a href="/sdk/server/setting-up-dev-environment">Set up ngrok</a> to expose your local server to the internet.

    You should be able to see the application in action at https\://\<ngrok\_identifier>.ngrok.io/.

    The finished application should look like this.

    <Frame>
      <video autoplay loop muted inline width="560" height="315">
        <source width="560" height="315" src="https://mintcdn.com/plivo/9TcugqK5W7G3A-xp/images/two-factor.mp4?fit=max&auto=format&n=9TcugqK5W7G3A-xp&q=85&s=520e7f7b48a0063c0cbee11c213631cb" type="video/mp4" data-path="images/two-factor.mp4" />
      </video>
    </Frame>
  </Tab>
</Tabs>
