Skip to content

Latest commit

 

History

History
90 lines (65 loc) · 2.97 KB

README.md

File metadata and controls

90 lines (65 loc) · 2.97 KB

Two-Factor Authentication

NuGet Version

A C# library for TOTP (RFC 6238) 2-factor authentication.

Installation

Visual Studio Package Manager Console:

Install-Package MarkoPapic.TwoFactorAuthentication

dotnet CLI:

dotnet add package MarkoPapic.TwoFactorAuthentication

Usage

Authenticator app

To generate a new authenticator app key:

TwoFactorAuthenticationManager twoFactorAuthenticationManager = new TwoFactorAuthenticationManager();
string authenticatorKey = twoFactorAuthenticationManager.AuthenticatorApp.GenerateKey();

The authenticatorKey should be entered in an authenticator app. Then, to validate a code generated by an authenticator app:

bool isCodeValid = twoFactorAuthenticationManager.AuthenticatorApp.ValidateCode(key, code);

Where code it the code generated by an authenticator app.

Message based

To generate a TOTP to be sent to the user (via SMS, email...):

TwoFactorAuthenticationManager twoFactorAuthenticationManager = new TwoFactorAuthenticationManager();
string totp = twoFactorAuthenticationManager.Message.GenerateTotp(userKey);

Where userKey is a Base32 encoded string that is uniquely associated to this user. This key should be provided by you. Then, to validate the TOTP sent by the user:

bool isTotpValid = twoFactorAuthenticationManager.Message.ValidateCode(userKey, totp);

Where userKey is the same key you used to generate the TOTP, and totp is the TOTP code generated in the previous step.

Configuration

You can configure the following parameters:

  • MessageTotpDuration: The duration for which message-based TOTPs should be valid. Default is 300 seconds.
  • AuthenticatorTotpVarianceAllowed: Allows up to the specified adjacent intervals to be checked when validating authenticator app TOTPs. This can make up for delays caused by latency or clock missmatch. Default is 0.
  • MessageTotpVarianceAllowed: Allows up to the specified adjacent intervals to be checked when validating message-based TOTPs. This can make up for delays caused by latency or clock missmatch. Default is 0.

Example:

TwoFactorAuthenticationManager twoFactorAuthenticationManager = new TwoFactorAuthenticationManager(new TwoFactorAuthenticationOptions
    {
        MessageTotpDuration = 500,
        MessageTotpVarianceAllowed = 1,
        AuthenticatorTotpVarianceAllowed = 0
    });

Using .Net Core Dependency Injection

You can use the .NET Core middleware to register TwoFactorAuthenticationManager as a service available via .NET dependency injection:

public void ConfigureServices(IServiceCollection services)
{
   // ...

    services.AddTwoFactorAuthentication();

    services.Configure<TwoFactorAuthenticationOptions>(options =>
    {
        options.MessageTotpDuration = 500;
    });
    
    // ...
}