Simple, easy to use server-side/desktop two-factor authentication library for .NET that works with authenticator apps e.g. from Google, from Microsoft, Authy or LastPass.
Install-Package TwoFactorAuthenticator
Also see additional example projects at
- TwoFactorAuthenticator.WinformsExample
- TwoFactorAuthenticator.WpfExample
- TwoFactorAuthenticator.WebSample
key
should be stored by your application for future authentication and shouldn't be regenerated for
each request. The process of storing the private key is outside the scope of this library and is the
responsibility of the application.
using TwoFactorAuthenticator;
using TwoFactorAuthenticator.QrCoder;
string key = Guid.NewGuid().ToString().Replace("-", "").Substring(0, 10);
Authenticator tfa = new Authenticator();
QrCoderSetupCodeGenerator qrscg = new QrCoderSetupCodeGenerator { PixelsPerModule = 3 };
SetupCode setupInfo = tfa.GenerateSetupCode("Test Two Factor", "user@example.com", key, false);
string qrCodeImageUrl = setupInfo.GenerateQrCodeUrl(qrscg);
using (MemoryStream ms = new MemoryStream(setupCode.GetQrCodeImageData(qrscg)))
{
qrCodePictureBox.Image = Image.FromStream(ms);
}
this.setupInfo.Text = "Account: " + setupCode.Account + System.Environment.NewLine +
"Encoded Key: " + setupCode.ManualEntryKey;
Authenticator tfa = new Authenticator();
PasswordToken token = tfa.GetCurrentPIN(key);
using (var unsafeToken = UnsafeToken.FromPasswordToken(token))
{
string pin = unsafeToken.ToString();
}
string input = "123456";
Authenticator tfa = new Authenticator();
PasswordToken token = PasswordToken.FromPassCode(int.Parse(input));
bool result = tfa.ValidateTwoFactorPIN(key, token);
- Breaking changes:
TwoFactorAuthenticator
should not be named like its namespace (created collision); new name is justAuthenticator
- Changed interface to use secured
PasswordToken
instead of primitive string
- Introduced
UnsafeToken
for generation / UI purposes - Introduced
FactorControl
for WinForms
- Forked and separated into two packages
- Lowest supported versions are now netstandard2.0 and .Net 4.7.2.
- Don't use the secret key and
ManualEntryKey
interchangeably.ManualEntryKey
is used to enter into the authenticator app when scanning a QR code is impossible and is derived from the secret key (discussion example)