# .NET Core C# Two-factor Authentication Quickstart

> \[!WARNING]
>
> As of November 2022, Twilio no longer provides support for Authy SMS/Voice-only customers. Customers who were also using Authy TOTP or Push prior to March 1, 2023 are still supported. The Authy API is now closed to new customers and will be fully deprecated in the future.
>
> For new development, we encourage you to use the [Verify v2 API](/docs/verify/api).
>
> Existing customers will not be impacted at this time until Authy API has reached End of Life. For more information about migration, see [Migrating from Authy to Verify for SMS](https://www.twilio.com/blog/migrate-authy-to-verify).

Adding two-factor authentication to your application is the easiest way to increase security and trust in your product without unnecessarily burdening your users. This quickstart guides you through building an [ASP.NET Core](https://dotnet.microsoft.com/en-us/download), [AngularJS](https://angularjs.org/), and [SQL Server](https://www.microsoft.com/en-us/sql-server/sql-server-2019) application that restricts access to a URL. Four [Authy API channels](/docs/verify/authentication-channels) are demoed: SMS, Voice, Soft Tokens and Push Notifications.

Ready to protect your toy app's users from nefarious balaclava wearing hackers? Dive in!

## Sign Into - or Sign Up For - a Twilio Account

Create a new Twilio account (you can sign up for a [free Twilio trial](/try-twilio)), or sign into [an existing Twilio account](https://www.twilio.com/console).

### Create a New Authy Application

Once logged in, visit the [Authy Console](https://www.twilio.com/console/authy/applications). Click on the red 'Create New Application' (or big red plus ('+') if you already created one) to create a new Authy application then name it something memorable.

![Authy dashboard with message 'You have no Authy applications' and 'Create Application' button.](https://docs-resources.prod.twilio.com/029c875193dd2fda38477674df469f18c933db29907845bc69d1f67e5fcb1e2b.png)

You'll automatically be transported to the **Settings** page next. Click the eyeball icon to reveal your Production API Key.

![General settings page showing production API key with reveal option.](https://docs-resources.prod.twilio.com/dd7f3a45399b71568b29ed2f993fc1b7c254a7a61477e2de544b66b7cb31d00b.png)

Copy your Production API Key to a safe place, you will use it during application setup.

## Setup Authy on Your Device

This two-factor authentication demos two channels which require an installed Authy app to test: Soft tokens and push authentications. While SMS and voice channels will work without the client, to try out all four authentication channels download and install the Authy app for Desktop or Mobile:

* [Download Authy App](https://authy.com/download/)

## Clone and Setup the Application

Start by [cloning our repository.](https://github.com/TwilioDevEd/account-security-csharp) Then, enter the directory and install dependencies:

```bash
git clone https://github.com/TwilioDevEd/account-security-csharp.git
cd account-security-csharp/src/AccountSecurity
dotnet restore
```

Next, open the file `appsettings.json`. There, **edit** the `AuthyApiKey`, pasting in the API Key from the above step (in the console), and **save** .

```json title="Add Your Application API Key" description="Enter the API Key from the Account Security console."
{
  "Logging": {
    "LogLevel": {
      "Default": "Warning"
    }
  },
  "AllowedHosts": "*",
  "ConnectionStrings": {
    "DefaultConnection": "Server=127.0.0.1;Database=account_security;Trusted_Connection=True;MultipleActiveResultSets=true;Integrated Security=False;User ID=sa;Password=yourStrong(!)Password"
  },
  "AuthyApiKey": "Your-Authy-Api-Key"
}
```

## Install and Launch SQL Server

When a user registers with your application, a request is made to Twilio to add that user to your App, and a `user_id` is returned. In this demo, we'll store the returned `user_id` in an MSSQL database.\
On Windows, you can install the free SQL Server Express:

* [Install SQL Server Express for Windows](https://www.microsoft.com/en-us/sql-server/sql-server-2019)

On Linux or Mac, run it as a docker container:

```bash
docker run -e 'ACCEPT_EULA=Y' -e 'SA_PASSWORD=yourStrong(!)Password' \

-p 1433:1433 --name mssql -d microsoft/mssql-server-linux:latest
```

> \[!WARNING]
>
> Make sure your `DefaultConnection` connection string in `appsettings.json` is correct for your SQL Server installation. You may need to change the `Server` to `localhost\\SQLEXPRESS` if running MSSQL Server Express on Windows. Or, you may need to change the password if you selected a different one when starting your Docker container.

Run the database migrations:

```bash
dotnet ef database update -v
```

Once you have added your API Key, you are ready to run! Run the app with:

```bash
dotnet run --environment development
```

## Try the .NET Core C# Two-Factor Demo

With your phone (optionally with the Authy client installed) nearby, open a new browser tab and navigate to [https://localhost:5001/register/](https://localhost:5001/register/)

Enter your information and invent a password, then hit 'Register'. Your information is passed to Twilio (you will be able to see your user [immediately in the console](https://www.twilio.com/console/authy/applications/)), and the application is returned a `user_id`.

Now visit [https://localhost:5001/login/](https://localhost:5001/login/) and login. You'll be presented with a happy screen:

![Token verification options: SMS, Voice, Push Auth, and Verify button.](https://docs-resources.prod.twilio.com/04aaadf5246b991095eed6ed1a7dbb06a183a169a1a2798bad8982ca0f1c0bb0.png)

If your phone has the Authy app installed, you can immediately enter a soft token from the client to Verify. Additionally, you can try a push authentication by pushing the labeled button.

If you do not have the Authy app installed, the SMS and voice channels will also work in providing a token. To try different channels, you can logout to start the process again.

```cs title="Two Factor Authentication Channels"
using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using AccountSecurity.Models;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;


namespace AccountSecurity.Services
{
  public interface IAuthy
  {
    Task<string> registerUserAsync(RegisterViewModel user);
    Task<TokenVerificationResult> verifyTokenAsync(string authyId, string token);
    Task<TokenVerificationResult> verifyPhoneTokenAsync(string phoneNumber, string countryCode, string token);
    Task<string> sendSmsAsync(string authyId);
    Task<string> phoneVerificationCallRequestAsync(string countryCode, string phoneNumber);
    Task<string> phoneVerificationRequestAsync(string countryCode, string phoneNumber);
    Task<string> createApprovalRequestAsync(string authyId);
    Task<object> checkRequestStatusAsync(string onetouch_uuid);
  }

  public class Authy : IAuthy
  {
    private readonly IConfiguration Configuration;
    private readonly IHttpClientFactory ClientFactory;
    private readonly ILogger<Authy> logger;
    private readonly HttpClient client;

    public string message { get; private set; }

    public Authy(IConfiguration config, IHttpClientFactory clientFactory, ILoggerFactory loggerFactory)
    {
      Configuration = config;
      logger = loggerFactory.CreateLogger<Authy>();

      ClientFactory = clientFactory;
      client = ClientFactory.CreateClient();
      client.BaseAddress = new Uri("https://api.authy.com");
      client.DefaultRequestHeaders.Add("Accept", "application/json");
      client.DefaultRequestHeaders.Add("user-agent", "Twilio Account Security C# Sample");

      // Get Authy API Key from Configuration
      client.DefaultRequestHeaders.Add("X-Authy-API-Key", Configuration["AuthyApiKey"]);
    }

    public async Task<string> registerUserAsync(RegisterViewModel user)
    {
      var userRegData = new Dictionary<string, string>() {
                { "email", user.Email },
                { "country_code", user.CountryCode },
                { "cellphone", user.PhoneNumber }
            };
      var userRegRequestData = new Dictionary<string, object>() { };
      userRegRequestData.Add("user", userRegData);
      var encodedContent = new FormUrlEncodedContent(userRegData);

      var result = await client.PostAsJsonAsync("/protected/json/users/new", userRegRequestData);

      logger.LogDebug(result.Content.ReadAsStringAsync().Result);

      result.EnsureSuccessStatusCode();

      var response = await result.Content.ReadAsAsync<Dictionary<string, object>>();

      return JObject.FromObject(response["user"])["id"].ToString();
    }

    public async Task<TokenVerificationResult> verifyTokenAsync(string authyId, string token)
    {
      var result = await client.GetAsync($"/protected/json/verify/{token}/{authyId}");

      logger.LogDebug(result.ToString());
      logger.LogDebug(result.Content.ReadAsStringAsync().Result);

      var message = await result.Content.ReadAsStringAsync();

      if (result.StatusCode == HttpStatusCode.OK)
      {
        return new TokenVerificationResult(message);
      }

      return new TokenVerificationResult(message, false);
    }

    public async Task<TokenVerificationResult> verifyPhoneTokenAsync(string phoneNumber, string countryCode, string token)
    {
      var result = await client.GetAsync(
          $"/protected/json/phones/verification/check?phone_number={phoneNumber}&country_code={countryCode}&verification_code={token}"
      );

      logger.LogDebug(result.ToString());
      logger.LogDebug(result.Content.ReadAsStringAsync().Result);

      var message = await result.Content.ReadAsStringAsync();

      if (result.StatusCode == HttpStatusCode.OK)
      {
        return new TokenVerificationResult(message);
      }

      return new TokenVerificationResult(message, false);
    }

    public async Task<string> sendSmsAsync(string authyId)
    {
      var result = await client.GetAsync($"/protected/json/sms/{authyId}?force=true");

      logger.LogDebug(result.ToString());

      result.EnsureSuccessStatusCode();

      return await result.Content.ReadAsStringAsync();
    }

    public async Task<string> phoneVerificationCallRequestAsync(string countryCode, string phoneNumber)
    {
      var result = await client.PostAsync(
          $"/protected/json/phones/verification/start?via=call&country_code={countryCode}&phone_number={phoneNumber}",
          null
      );

      var content = await result.Content.ReadAsStringAsync();

      logger.LogDebug(result.ToString());
      logger.LogDebug(content);

      result.EnsureSuccessStatusCode();

      return await result.Content.ReadAsStringAsync();
    }

    public async Task<string> phoneVerificationRequestAsync(string countryCode, string phoneNumber)
    {
      var result = await client.PostAsync(
          $"/protected/json/phones/verification/start?via=sms&country_code={countryCode}&phone_number={phoneNumber}",
          null
      );

      var content = await result.Content.ReadAsStringAsync();

      logger.LogDebug(result.ToString());
      logger.LogDebug(content);

      result.EnsureSuccessStatusCode();

      return await result.Content.ReadAsStringAsync();
    }

    public async Task<string> createApprovalRequestAsync(string authyId)
    {
      var requestData = new Dictionary<string, string>() {
                { "message", "OneTouch Approval Request" },
                { "details", "My Message Details" },
                { "seconds_to_expire", "300" }
            };

      var result = await client.PostAsJsonAsync(
          $"/onetouch/json/users/{authyId}/approval_requests",
          requestData
      );

      logger.LogDebug(result.ToString());
      var str_content = await result.Content.ReadAsStringAsync();
      logger.LogDebug(str_content);

      result.EnsureSuccessStatusCode();

      var content = await result.Content.ReadAsAsync<Dictionary<string, object>>();
      var approval_request_data = (JObject)content["approval_request"];

      return (string)approval_request_data["uuid"];
    }

    public async Task<object> checkRequestStatusAsync(string onetouch_uuid)
    {
      var result = await client.GetAsync($"/onetouch/json/approval_requests/{onetouch_uuid}");
      logger.LogDebug(result.ToString());
      var str_content = await result.Content.ReadAsStringAsync();
      logger.LogDebug(str_content);

      result.EnsureSuccessStatusCode();

      return await result.Content.ReadAsAsync<object>();
    }
  }

  public class TokenVerificationResult
  {
    public TokenVerificationResult(string message, bool succeeded = true)
    {
      this.Message = message;
      this.Succeeded = succeeded;
    }

    public bool Succeeded { get; set; }
    public string Message { get; set; }
  }
}
```

And there you go, two-factor authentication is on and your .NET Core C# App is protected!

## What's Next?

Now that you are keeping the hackers out of this demo app using two-factor authentication, you can find all of the detailed descriptions for options and API calls in our [Authy API Reference](/docs/authy/api). If you're also building a registration flow, also check out our [Twilio Verify](/docs/verify) product and the [Verification Quickstart](/docs/verify/quickstarts/csharp-asp-net-core-mvc) which uses this codebase.

For additional guides and tutorials on account security and other products, in C# and in other languages, [take a look at the Docs](/docs).
