How to Implement Two Factor Authentication Via Email in ASP.Net Core 2?
Asked Answered
H

1

7

I am using ASP.NET Core 2.2 for a web server, In each time a user login to the website, after entering a correct email & password, I need to send a message containing a 4-digits PIN Code to user email, to use it as Email Two Factor Authentication, and this PIN Code, should expire after 10 minutes after sending it.

I can do this manually (generating random PIN Codes, saving them in Database, verifying them using if statements, etc...), this would work, but I created this question to ask how to do this using ASP.NET Core 2 available features (which can spare the database table for me).

I tried UserManager.GenerateTwoFactorTokenAsync(TUser, String) Method, to generate a token and send it to email:

var token = await _userManager.GenerateTwoFactorTokenAsync(user, "Default");
SendLoginTokenToUserEmail(user, token);

and used UserManager.VerifyTwoFactorTokenAsync(TUser, String, String) to verify it:

var verified = await _userManager.VerifyTwoFactorTokenAsync(user, "Default", token);

This worked perfectly, but my problem was that the generated token wasn't a 4-Digit PIN Code, and its expiration time wasn't 10 minutes (I think the default is 1 day).

So, my Question is: How to Customize the generated token by UserManager for Two Factor Authentication in ASP.NET Core 2.2?

Can this done by creating a custom token provider? (I am using Default Token Provider here) if so, what is the steps to do so? I spent hours surfing Docs and ASP.NET Core 2 Articles, but did't find what I need.

PS: If there is any other way other than UserManager, I am all ears, but I thought this might be the best way, especially UserManager is used everywhere in our system (for login, password-reset, etc...).

Hardhack answered 7/5, 2019 at 7:39 Comment(0)
L
1

If you need OTP then use "Email" or "Phone" as a tokenProvider

var token = await _userManager.GenerateTwoFactorTokenAsync(user, "Email");
SendLoginTokenToUserEmail(user, token);

And Verify token using same tokenProvider

var verified = await _userManager.VerifyTwoFactorTokenAsync(user, "Email", token);

The maximum attempts (default is 5).

The 2FA codes are generated using Time-based One-time Password Algorithm and codes are valid for six minutes.

Lathery answered 28/11, 2023 at 16:45 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.