Junior — Middle
Tell me about the approach to implementing a mechanism for sending one-time codes for two-factor authentication and possible solutions to problems associated with this process.
sobes.tech AI
Answer from AI
The mechanism for sending one-time codes (OTP) for two-factor authentication typically involves the following steps:
- Generating a random code with a limited validity period.
- Sending the code to the user via SMS, email, or push notification.
- Verifying the code entered by the user on the server.
Possible issues and solutions:
- Delivery delays: use reliable messaging services and consider resending the code.
- Code security: generate sufficiently long and random codes, store them encrypted, and limit the number of input attempts.
- Code expiration: set a short TTL (e.g., 5 minutes) to minimize the risk of compromise.
- Reusing codes: after successful verification, the code should be invalidated.
Example of OTP generation and verification in C#:
public class OtpService
{
private Dictionary<string, (string code, DateTime expiry)> otpStorage = new();
public string GenerateOtp(string userId)
{
var code = new Random().Next(100000, 999999).ToString();
otpStorage[userId] = (code, DateTime.UtcNow.AddMinutes(5));
return code;
}
public bool ValidateOtp(string userId, string code)
{
if (otpStorage.TryGetValue(userId, out var entry))
{
if (entry.code == code && entry.expiry > DateTime.UtcNow)
{
otpStorage.Remove(userId); // invalidate the code
return true;
}
}
return false;
}
}