Part-3 | Asp.Net Core Identity Series[.NET 7] | Sending Two-Factor Authentication(2FA) Code To Email
The main objectives of this article are:
- Sending Two-Factor Authentication(2FA) Code To Email
Enable Email 2FA:
In Asp.Net Core Identity application to enable email Two-Factor Authentication, make sure our 'AspNetUser' table following fields has appropriate data:
- Email - Should not be empty or null
- EmailConfrimed - must be true
- TwoFactorEnabled - must be true.
Now if we try to login into our application we can see a page to enter the 2FA code like below
Send Two-Factor Authentication(2FA) Code To Email:
Now let's update the code in 'OnGetAsync()' method in 'Areas/Identity/Pages/Account/LoginWith2faModel.cshtml.cs' as below.
Areas/Identity/Pages/Account/LoginWith2faModel.cshtml.cs:
public async Task<IActionResult> OnGetAsync(bool rememberMe, string returnUrl = null) { // Ensure the user has gone through the username & password screen first var user = await _signInManager.GetTwoFactorAuthenticationUserAsync(); if (user == null) { throw new InvalidOperationException($"Unable to load two-factor authentication user."); } var providers = await _userManager.GetValidTwoFactorProvidersAsync(user); if (providers.Any(_ => _ == "Email")) { var token = await _userManager.GenerateTwoFactorTokenAsync(user, "Email"); await _emailSender.SendEmailAsync(user.Email, "2FA Code", $"<h3 >{token}</h3>."); } else { throw new InvalidOperationException($"Unable to load two-factor authentication user."); } ReturnUrl = returnUrl; RememberMe = rememberMe; return Page(); }
- Line(11-22) are newly added code, the remaining lines of code are existing code.
- (Line: 4) The 'GetTwoFactorAuthenticationUserAsync()' method fetches the user information. So when the user tried to log in with 'username' and 'password', if 'TwoFactorEnabled' then it will create a cookie like 'Identity.TwoFactorUserId', So 'GetTwoFactorAuthenticationUserAsync()' method uses the 'Identity.TwoFactorUserId' to fetch user information.
- (Line: 11) The 'GetValidTwoFactorProviderAsync()' method gives collection of 2fa providers for the user like 'Email', 'Phone'.
- (Line: 13-18) Checking 'Email' provider existed or not. Using 'GenerateTwoFactorTokenAsync()' method generates 2fa code for 'Email'. Finally, send the code to the user's email address.
Verify Email Two-Factor Authentication Code:
Now let's update the code in 'OnPostAsync()' method in 'Areas/Identity/Pages/Account/LoginWith2faModel.cshtml.cs' as below.
Areas/Identity/Pages/Account/LoginWith2faModel.cshtml.cs:
public async Task<IActionResult> OnPostAsync(bool rememberMe, string returnUrl = null) { if (!ModelState.IsValid) { return Page(); } returnUrl = returnUrl ?? Url.Content("~/"); var user = await _signInManager.GetTwoFactorAuthenticationUserAsync(); if (user == null) { throw new InvalidOperationException($"Unable to load two-factor authentication user."); } var authenticatorCode = Input.TwoFactorCode.Replace(" ", string.Empty).Replace("-", string.Empty); //var result = await _signInManager.TwoFactorAuthenticatorSignInAsync(authenticatorCode, rememberMe, Input.RememberMachine); var result = await _signInManager.TwoFactorSignInAsync("Email", authenticatorCode, rememberMe, Input.RememberMachine); var userId = await _userManager.GetUserIdAsync(user); if (result.Succeeded) { _logger.LogInformation("User with ID '{UserId}' logged in with 2fa.", user.Id); return LocalRedirect(returnUrl); } else if (result.IsLockedOut) { _logger.LogWarning("User with ID '{UserId}' account locked out.", user.Id); return RedirectToPage("./Lockout"); } else { _logger.LogWarning("Invalid authenticator code entered for user with ID '{UserId}'.", user.Id); ModelState.AddModelError(string.Empty, "Invalid authenticator code."); return Page(); } }
- Here we changed like commented the (Line: 18) and added the code at (Line: 19) remaining code is the default.
- (Line: 19) The 'TwoFactorSignInAsync' method verifies whether our code is valid or not.
Check Email 2FA Flow:
(Step 1) Go login page and enter your credentials.
(Step 2) Now you can see the Two-Factor Authentication Page
(Step 3)Check your email for Two-Factor Authentication Code
In the next article, we are going implement sending a 2fa authentication code to the Phone.
Support Me!
Buy Me A Coffee
PayPal Me
Video Session:
Wrapping Up:
Hopefully, I think this article delivered some useful information on the Asp.Net Core Identity In Razor Pages. using I love to have your feedback, suggestions, and better techniques in the comment section below
Refer:
Part -1 | Asp.Net Core Identity Series[.NET 7] Introduction & Project Setup
Part-2 | Asp.Net Core Identity Series[.NET 7] | Registration Email Confirmation
Part-4 | Asp.Net Core Identity Series[.NET 7] | Sending Two-Factor Authentication(2FA) Code To Phone
Part-5 | Asp.Net Core Identity Series[.NET 7] | Google Authentication
Part-2 | Asp.Net Core Identity Series[.NET 7] | Registration Email Confirmation
Part-4 | Asp.Net Core Identity Series[.NET 7] | Sending Two-Factor Authentication(2FA) Code To Phone
Part-5 | Asp.Net Core Identity Series[.NET 7] | Google Authentication
Part - 6 | Asp.Net Core Identity Series[.NET 7] | Facebook Authentication
Part - 7 | Asp.Net Core Identity Series[.NET 7] | Twitter Authentication
Part - 7 | Asp.Net Core Identity Series[.NET 7] | Twitter Authentication
Comments
Post a Comment