Support us .Net Basics C# SQL ASP.NET Aarvi MVC Slides C# Programs Subscribe Download

External login email confirmation in asp.net core

Suggested Videos
Part 111 - Why email confirmation is important | Text | Slides
Part 112 - Block login if email is not confirmed in asp.net core | Text | Slides
Part 113 - ASP.NET Core email confirmation | Text | Slides

In this video we will discuss how to confirm the email received from external login providers such as Google, Facebook etc.

When we use external providers like Google or Facebook to login, we receive the user email from these external login provider. We then use this email to create a local user account.


Upon creating a local user account, send email confirmation link. If the email address is not confirmed, do not allow the user to login and display the error - Email not confirmed yet.

On the other hand, if the email address is confirmed, create an external login (AspNetUserLogins) and sign-in the user.


external login email confirmation in asp.net core

[AllowAnonymous]
public async Task<IActionResult>
ExternalLoginCallback(string returnUrl = null, string remoteError = null)
{
    returnUrl = returnUrl ?? Url.Content("~/");

    LoginViewModel loginViewModel = new LoginViewModel
    {
        ReturnUrl = returnUrl,
        ExternalLogins =
        (await signInManager.GetExternalAuthenticationSchemesAsync()).ToList()
    };

    if (remoteError != null)
    {
        ModelState.AddModelError(string.Empty,
            $"Error from external provider: {remoteError}");

        return View("Login", loginViewModel);
    }

    var info = await signInManager.GetExternalLoginInfoAsync();
    if (info == null)
    {
        ModelState.AddModelError(string.Empty,
            "Error loading external login information.");

        return View("Login", loginViewModel);
    }

    var email = info.Principal.FindFirstValue(ClaimTypes.Email);
    ApplicationUser user = null;

    if (email != null)
    {
        user = await userManager.FindByEmailAsync(email);

        if (user != null && !user.EmailConfirmed)
        {
            ModelState.AddModelError(string.Empty, "Email not confirmed yet");
            return View("Login", loginViewModel);
        }
    }

    var signInResult = await signInManager.ExternalLoginSignInAsync(
                                info.LoginProvider, info.ProviderKey,
                                isPersistent: false, bypassTwoFactor: true);

    if (signInResult.Succeeded)
    {
        return LocalRedirect(returnUrl);
    }
    else
    {
        if (email != null)
        {
            if (user == null)
            {
                user = new ApplicationUser
                {
                    UserName = info.Principal.FindFirstValue(ClaimTypes.Email),
                    Email = info.Principal.FindFirstValue(ClaimTypes.Email)
                };

                await userManager.CreateAsync(user);

                // After a local user account is created, generate and log the
                // email confirmation link
                var token = await userManager.GenerateEmailConfirmationTokenAsync(user);

                var confirmationLink = Url.Action("ConfirmEmail", "Account",
                                new { userId = user.Id, token = token }, Request.Scheme);

                logger.Log(LogLevel.Warning, confirmationLink);

                ViewBag.ErrorTitle = "Registration successful";
                ViewBag.ErrorMessage = "Before you can Login, please confirm your " +
                    "email, by clicking on the confirmation link we have emailed you";
                return View("Error");
            }

            await userManager.AddLoginAsync(user, info);
            await signInManager.SignInAsync(user, isPersistent: false);

            return LocalRedirect(returnUrl);
        }

        ViewBag.ErrorTitle = $"Email claim not received from: {info.LoginProvider}";
        ViewBag.ErrorMessage = "Please contact support on Pragim@PragimTech.com";

        return View("Error");
    }
}

[HttpGet]
[AllowAnonymous]
public async Task<IActionResult> ConfirmEmail(string userId, string token)
{
    if (userId == null || token == null)
    {
        return RedirectToAction("index", "home");
    }

    var user = await userManager.FindByIdAsync(userId);

    if (user == null)
    {
        ViewBag.ErrorMessage = $"The User ID {userId} is invalid";
        return View("NotFound");
    }

    var result = await userManager.ConfirmEmailAsync(user, token);

    if (result.Succeeded)
    {
        return View();
    }

    ViewBag.ErrorTitle = "Email cannot be confirmed";
    return View("Error");
}

asp.net core tutorial for beginners

No comments:

Post a Comment

It would be great if you can help share these free resources