One-Time Password (OTP): The Key to Secure Logins via Email and Mobile in .NET Core with a step-by-step guide
Digits identify you in this digital world
Let’s face it — security is a top priority in today’s digital age. Whether you’re logging into your favorite app or accessing sensitive data, ensuring secure authentication is essential. One of the most widely-used methods to fortify security is the One-Time Password (OTP).
Now, imagine a user trying to log in, and depending on whether they use their email or mobile, they receive an OTP to verify their identity. Seems straightforward, right? But how does it work behind the scenes in .NET Core?
In this blog, we’ll break it down step-by-step, and show you how to implement this functionality in a fancy yet practical way — where users get their OTP via email or mobile depending on their login method. Let’s jump in and make things secure!
📌Explore more at: https://dotnet-fullstack-dev.blogspot.com/
🌟 Clapping would be appreciated! 🚀
Why OTP for Authentication?
Before we dive into the code, let’s quickly understand the “why”. OTPs are widely used for two main reasons:
- Security: Since OTPs are short-lived and unique for every login attempt, they provide an extra layer of security.
- Convenience: Users no longer have to remember complicated passwords; all they need is the code sent to their registered device.
With our growing reliance on apps for everything from banking to social media, OTPs ensure that only the right person is accessing their account.
The Requirements: OTP via Email or Mobile
Here’s the scenario:
- If a user logs in using their email, the system generates and sends an OTP to their email inbox.
- If a user logs in using their mobile number, the OTP gets sent via SMS to their mobile device.
Sounds easy, right? But there’s a lot happening under the hood, and we’ll take a look at how to handle it in .NET Core.
Setting Up the Project in .NET Core
To get started, create a .NET Core project and install the necessary packages for sending emails and SMS.
Step 1: Generate the OTP
First things first — let’s create a method that generates the OTP. We’ll keep it simple by generating a random 6-digit number.
public class OtpService
{
public string GenerateOtp()
{
Random random = new Random();
return random.Next(100000, 999999).ToString();
}
}
Here, we’re generating a 6-digit OTP that will be sent to the user based on their login method.
Step 2: Sending OTP via Email
Let’s assume the user logged in using their email. In that case, we’ll send the OTP to their email address. For this, we can use SMTP to send emails from our application.
public class EmailService
{
public async Task SendEmailAsync(string email, string otp)
{
var smtpClient = new SmtpClient("smtp.your-email-provider.com")
{
Port = 587,
Credentials = new NetworkCredential("your-email@example.com", "password"),
EnableSsl = true,
};
var mailMessage = new MailMessage
{
From = new MailAddress("your-email@example.com"),
Subject = "Your OTP Code",
Body = $"Your OTP code is {otp}",
IsBodyHtml = true,
};
mailMessage.To.Add(email);
await smtpClient.SendMailAsync(mailMessage);
}
}
This code will send an email containing the OTP to the user. Easy, right? Now the user gets their OTP right in their inbox.
Step 3: Sending OTP via Mobile (SMS)
If the user logs in using their mobile number, we’ll send the OTP via SMS. You can use an SMS provider like Twilio or AWS SNS for this. Here’s an example using Twilio:
public class SmsService
{
public async Task SendSmsAsync(string mobileNumber, string otp)
{
var accountSid = "your-twilio-account-sid";
var authToken = "your-twilio-auth-token";
TwilioClient.Init(accountSid, authToken);
var message = await MessageResource.CreateAsync(
body: $"Your OTP code is {otp}",
from: new Twilio.Types.PhoneNumber("your-twilio-phone-number"),
to: new Twilio.Types.PhoneNumber(mobileNumber)
);
}
}
Now, depending on the user’s login method, they’ll get their OTP either via email or SMS. Magic!
Step 4: Putting It All Together
So how do we decide whether to send the OTP to email or mobile? Here’s how to make it happen:
public class LoginService
{
private readonly OtpService _otpService;
private readonly EmailService _emailService;
private readonly SmsService _smsService;
public LoginService(OtpService otpService, EmailService emailService, SmsService smsService)
{
_otpService = otpService;
_emailService = emailService;
_smsService = smsService;
}
public async Task SendOtp(string loginMethod, string value)
{
var otp = _otpService.GenerateOtp();
if (loginMethod == "email")
{
await _emailService.SendEmailAsync(value, otp);
}
else if (loginMethod == "mobile")
{
await _smsService.SendSmsAsync(value, otp);
}
}
}
- If the user logs in with email, the
SendOtp()
method sends the OTP to their email. - If the user logs in with mobile, the OTP is sent via SMS.
Step 5: The Final Flow
Here’s how it works:
- User logs in with either their email or mobile.
- Based on the input, the system generates a unique OTP.
- The OTP is sent to the appropriate communication channel (either email or SMS).
- The user enters the OTP to complete the authentication process.
Key Benefits of OTP Authentication
- Enhanced Security: OTPs are short-lived and unique, making them much harder to intercept or reuse.
- User-Friendly: Users don’t need to remember a password — just their OTP, which is sent to their device.
- Flexible: You can send OTPs via different channels, such as email, SMS, or even mobile apps.
Conclusion: OTPs Are the Future of Secure Logins
That’s it! You now have a solid understanding of how to implement OTP-based authentication in .NET Core. Depending on the user’s login method (email or mobile), the OTP is generated and sent to the appropriate channel.
Whether you’re building a secure banking app, a customer portal, or an e-commerce platform, OTP-based authentication is a powerful way to ensure only the right users are accessing your system. And with .NET Core, the implementation is simple yet effective.
What’s Next?
Please grab a cup of coffee. I have added posts on application security like JWT authentication and authorizations, OpenId Connect, OAuth 2.0 and how to implement expiration and retry mechanisms to further enhance security.
Have a look and Feel free to add your thoughts!