Securing Your C# Application with 2FA: Google Authenticator, SMS, and Email

Securing Your C# Application with 2FA Google Authenticator, SMS, and Email

In today’s world, securing user accounts with just a password is no longer enough. Implementing Two-Factor Authentication (2FA) adds an extra layer of protection to your C# applications. In this post, I’ll walk you through how to implement 2FA using Google Authenticator, SMS, and Email.

 

1. Google Authenticator

The Google Authenticator app provides a Time-Based One-Time Password (TOTP) system. You can easily integrate this into your .NET applications using the Google.Authenticator NuGet package.

First, install the package:

PowerShell
				dotnet add package Google.Authenticator
			

Then, generate a secret key and QR code for users to scan:

C#
				public class TwoFactorAuthService
{
    private const AppName = "MyApp";

    public string GenerateSecretKey()
    {
        var tfa = new TwoFactorAuthenticator();
        return tfa.GenerateSetupCode(AppName, "user@example.com", Guid.NewGuid().ToString(), false, 300).ManualEntryKey;
    }

    public string GenerateQrCode(sting secretKey, string userEmail)
    {
        var tfa = new TwoFactorAuthenticator();
        var setupInfo = tfa.GenerateSetupCode(AppName, userEmail, secretKey, false, 300);
        return setupInfo.QrCodeSetupImageUrl;
    }
}
			

To validate the TOTP code:

C#
				public bool ValidateTOTP(string userInputCode, string secretKey)
{
    var tfa = new TwoFactorAuthenticator();
    return tfa.ValidateTwoFactorPIN(secretKey, userInputCode);
}
			

 

2. Sending OTP via SMS (Using Zenvia)

You can also offer SMS-based 2FA using Zenvia. This requires the Zenvia SDK, which can be installed via NuGet.

PowerShell
				donet add package Zenvia.SDK
			

Here’s how to send the OTP code via SMS:

C#
				public class SmsService()
{
    private readonly ZenviaClient _zenviaClient;
    private const string ZenviaApiToken = "your_zenvia_api_token";

    public SmsService()
    {
        _zenviaClient = new ZenviaClient(ZenviaApiToken);
    }

    public async Task SendOtpSmsAsync(string phoneNumber, string otp)
    {
        var smsMessage = new smsMessage()
        {
            From = "YourAppName",
            To = phoneNumber,
            Contents = new List<MessageContent> 
            {
                new MessageContent($"Your verification code is {otp}")
            }
        };

        await _zenviaClient.SendAsync(smsMessage);
    }
}
			

 

3. Email-Based 2FA

Finally, you can also send OTPs via Email. Here’s a simple implementation using SMTP:

C#
				public async Task SendOtpEmailAsync(NewEmail email)
{
	try
	{
		var message = new MimeMessage();
		message.From.Add(new MailboxAddress(configuracao.NomeSistema, email.Adress));
		message.To.AddRange(email.To.Select(x => MailboxAddress.Parse(x)));
		message.Cc.AddRange(email.Copy?.Select(c => MailboxAddress.Parse(c)));
		message.Subject = email.Title;
		message.Body = new TextPart(TextFormat.Html) { Text = email.Message };

		using var client = new SmtpClient();
		await client.ConnectAsync(configuration.Server, configuration.Port, configuration.Ssl);
		await client.AuthenticateAsync(configuration.User, configuration.Password);
		await client.SendAsync(message);
		await client.DisconnectAsync(true);
	}
	catch (Exception e)
	{
		Logger.LogError(e, "Error");
	}
}
			

 

Conclusion

By offering multiple 2FA options such as Google Authenticator, SMS, and Email, you’re allowing users to choose the method that best suits their needs, significantly improving the security of your application.

See you next time!

Share the Post:
plugins premium WordPress