Skip to contentSkip to navigationSkip to topbar
Rate this page:
On this page

.NET Core C# Two-factor Authentication Quickstart


(warning)

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.

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(link takes you to an external page).

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(link takes you to an external page), AngularJS(link takes you to an external page), and SQL Server(link takes you to an external page) application that restricts access to a URL. Four Authy API 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

sign-into---or-sign-up-for---a-twilio-account page anchor

Create a new Twilio account (you can sign up for a free Twilio trial), or sign into an existing Twilio account(link takes you to an external page).

Create a New Authy Application

create-a-new-authy-application page anchor

Once logged in, visit the Authy Console(link takes you to an external page). Click on the red 'Create New Aplication' (or big red plus ('+') if you already created one) to create a new Authy application then name it something memorable.

Authy create new application.

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

Account Security API Key.

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


Setup Authy on Your Device

setup-authy-on-your-device page anchor

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:


Clone and Setup the Application

clone-and-setup-the-application page anchor

Start by cloning our repository.(link takes you to an external page) Then, enter the directory and install dependencies:


_10
git clone https://github.com/TwilioDevEd/account-security-csharp.git
_10
cd account-security-csharp/src/AccountSecurity
_10
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 .

Add Your Application API Key

add-your-application-api-key page anchor

Enter the API Key from the Account Security console.


_12
{
_12
"Logging": {
_12
"LogLevel": {
_12
"Default": "Warning"
_12
}
_12
},
_12
"AllowedHosts": "*",
_12
"ConnectionStrings": {
_12
"DefaultConnection": "Server=127.0.0.1;Database=account_security;Trusted_Connection=True;MultipleActiveResultSets=true;Integrated Security=False;User ID=sa;Password=yourStrong(!)Password"
_12
},
_12
"AuthyApiKey": "Your-Authy-Api-Key"
_12
}


Install and Launch SQL Server

install-and-launch-sql-server page anchor

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:

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


_10
docker run -e 'ACCEPT_EULA=Y' -e 'SA_PASSWORD=yourStrong(!)Password' \
_10
_10
-p 1433:1433 --name mssql -d microsoft/mssql-server-linux:latest

(warning)

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:


_10
dotnet ef database update -v

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


_10
dotnet run --environment development


Try the .NET Core C# Two-Factor Demo

try-the-net-core-c-two-factor-demo page anchor

With your phone (optionally with the Authy client installed) nearby, open a new browser tab and navigate to https://localhost:5001/register/(link takes you to an external page)

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(link takes you to an external page)), and the application is returned a user_id.

Now visit https://localhost:5001/login/(link takes you to an external page) and login. You'll be presented with a happy screen:

Token Verification Page.

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 simply 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.

Two Factor Authentication Channels

two-factor-authentication-channels page anchor

_203
using System;
_203
using System.Collections.Generic;
_203
using System.Net;
_203
using System.Net.Http;
_203
using System.Threading.Tasks;
_203
using AccountSecurity.Models;
_203
using Microsoft.Extensions.Configuration;
_203
using Microsoft.Extensions.Logging;
_203
using Newtonsoft.Json;
_203
using Newtonsoft.Json.Linq;
_203
_203
_203
namespace AccountSecurity.Services
_203
{
_203
public interface IAuthy
_203
{
_203
Task<string> registerUserAsync(RegisterViewModel user);
_203
Task<TokenVerificationResult> verifyTokenAsync(string authyId, string token);
_203
Task<TokenVerificationResult> verifyPhoneTokenAsync(string phoneNumber, string countryCode, string token);
_203
Task<string> sendSmsAsync(string authyId);
_203
Task<string> phoneVerificationCallRequestAsync(string countryCode, string phoneNumber);
_203
Task<string> phoneVerificationRequestAsync(string countryCode, string phoneNumber);
_203
Task<string> createApprovalRequestAsync(string authyId);
_203
Task<object> checkRequestStatusAsync(string onetouch_uuid);
_203
}
_203
_203
public class Authy : IAuthy
_203
{
_203
private readonly IConfiguration Configuration;
_203
private readonly IHttpClientFactory ClientFactory;
_203
private readonly ILogger<Authy> logger;
_203
private readonly HttpClient client;
_203
_203
public string message { get; private set; }
_203
_203
public Authy(IConfiguration config, IHttpClientFactory clientFactory, ILoggerFactory loggerFactory)
_203
{
_203
Configuration = config;
_203
logger = loggerFactory.CreateLogger<Authy>();
_203
_203
ClientFactory = clientFactory;
_203
client = ClientFactory.CreateClient();
_203
client.BaseAddress = new Uri("https://api.authy.com");
_203
client.DefaultRequestHeaders.Add("Accept", "application/json");
_203
client.DefaultRequestHeaders.Add("user-agent", "Twilio Account Security C# Sample");
_203
_203
// Get Authy API Key from Configuration
_203
client.DefaultRequestHeaders.Add("X-Authy-API-Key", Configuration["AuthyApiKey"]);
_203
}
_203
_203
public async Task<string> registerUserAsync(RegisterViewModel user)
_203
{
_203
var userRegData = new Dictionary<string, string>() {
_203
{ "email", user.Email },
_203
{ "country_code", user.CountryCode },
_203
{ "cellphone", user.PhoneNumber }
_203
};
_203
var userRegRequestData = new Dictionary<string, object>() { };
_203
userRegRequestData.Add("user", userRegData);
_203
var encodedContent = new FormUrlEncodedContent(userRegData);
_203
_203
var result = await client.PostAsJsonAsync("/protected/json/users/new", userRegRequestData);
_203
_203
logger.LogDebug(result.Content.ReadAsStringAsync().Result);
_203
_203
result.EnsureSuccessStatusCode();
_203
_203
var response = await result.Content.ReadAsAsync<Dictionary<string, object>>();
_203
_203
return JObject.FromObject(response["user"])["id"].ToString();
_203
}
_203
_203
public async Task<TokenVerificationResult> verifyTokenAsync(string authyId, string token)
_203
{
_203
var result = await client.GetAsync($"/protected/json/verify/{token}/{authyId}");
_203
_203
logger.LogDebug(result.ToString());
_203
logger.LogDebug(result.Content.ReadAsStringAsync().Result);
_203
_203
var message = await result.Content.ReadAsStringAsync();
_203
_203
if (result.StatusCode == HttpStatusCode.OK)
_203
{
_203
return new TokenVerificationResult(message);
_203
}
_203
_203
return new TokenVerificationResult(message, false);
_203
}
_203
_203
public async Task<TokenVerificationResult> verifyPhoneTokenAsync(string phoneNumber, string countryCode, string token)
_203
{
_203
var result = await client.GetAsync(
_203
$"/protected/json/phones/verification/check?phone_number={phoneNumber}&country_code={countryCode}&verification_code={token}"
_203
);
_203
_203
logger.LogDebug(result.ToString());
_203
logger.LogDebug(result.Content.ReadAsStringAsync().Result);
_203
_203
var message = await result.Content.ReadAsStringAsync();
_203
_203
if (result.StatusCode == HttpStatusCode.OK)
_203
{
_203
return new TokenVerificationResult(message);
_203
}
_203
_203
return new TokenVerificationResult(message, false);
_203
}
_203
_203
public async Task<string> sendSmsAsync(string authyId)
_203
{
_203
var result = await client.GetAsync($"/protected/json/sms/{authyId}?force=true");
_203
_203
logger.LogDebug(result.ToString());
_203
_203
result.EnsureSuccessStatusCode();
_203
_203
return await result.Content.ReadAsStringAsync();
_203
}
_203
_203
public async Task<string> phoneVerificationCallRequestAsync(string countryCode, string phoneNumber)
_203
{
_203
var result = await client.PostAsync(
_203
$"/protected/json/phones/verification/start?via=call&country_code={countryCode}&phone_number={phoneNumber}",
_203
null
_203
);
_203
_203
var content = await result.Content.ReadAsStringAsync();
_203
_203
logger.LogDebug(result.ToString());
_203
logger.LogDebug(content);
_203
_203
result.EnsureSuccessStatusCode();
_203
_203
return await result.Content.ReadAsStringAsync();
_203
}
_203
_203
public async Task<string> phoneVerificationRequestAsync(string countryCode, string phoneNumber)
_203
{
_203
var result = await client.PostAsync(
_203
$"/protected/json/phones/verification/start?via=sms&country_code={countryCode}&phone_number={phoneNumber}",
_203
null
_203
);
_203
_203
var content = await result.Content.ReadAsStringAsync();
_203
_203
logger.LogDebug(result.ToString());
_203
logger.LogDebug(content);
_203
_203
result.EnsureSuccessStatusCode();
_203
_203
return await result.Content.ReadAsStringAsync();
_203
}
_203
_203
public async Task<string> createApprovalRequestAsync(string authyId)
_203
{
_203
var requestData = new Dictionary<string, string>() {
_203
{ "message", "OneTouch Approval Request" },
_203
{ "details", "My Message Details" },
_203
{ "seconds_to_expire", "300" }
_203
};
_203
_203
var result = await client.PostAsJsonAsync(
_203
$"/onetouch/json/users/{authyId}/approval_requests",
_203
requestData
_203
);
_203
_203
logger.LogDebug(result.ToString());
_203
var str_content = await result.Content.ReadAsStringAsync();
_203
logger.LogDebug(str_content);
_203
_203
result.EnsureSuccessStatusCode();
_203
_203
var content = await result.Content.ReadAsAsync<Dictionary<string, object>>();
_203
var approval_request_data = (JObject)content["approval_request"];
_203
_203
return (string)approval_request_data["uuid"];
_203
}
_203
_203
public async Task<object> checkRequestStatusAsync(string onetouch_uuid)
_203
{
_203
var result = await client.GetAsync($"/onetouch/json/approval_requests/{onetouch_uuid}");
_203
logger.LogDebug(result.ToString());
_203
var str_content = await result.Content.ReadAsStringAsync();
_203
logger.LogDebug(str_content);
_203
_203
result.EnsureSuccessStatusCode();
_203
_203
return await result.Content.ReadAsAsync<object>();
_203
}
_203
}
_203
_203
public class TokenVerificationResult
_203
{
_203
public TokenVerificationResult(string message, bool succeeded = true)
_203
{
_203
this.Message = message;
_203
this.Succeeded = succeeded;
_203
}
_203
_203
public bool Succeeded { get; set; }
_203
public string Message { get; set; }
_203
}
_203
}

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


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. If you're also building a registration flow, also check out our Twilio Verify product and the Verification Quickstart 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.


Rate this page: