How to fix GetExternalLoginInfoAsync Always Returns null in ASP.NET MVC

By FoxLearn 2/18/2024 1:22:26 AM   463
I've got a problem, the GetExternalLoginInfoAsync method always return null when using single sign on (SSO) with google or facebook

I don't know why, I've tested the local host works perfectly

But when i publish my site on IIS, then sometime it's work ok and some days i can't login with single sign on (SSO)

I don't know why but when i restart the application pool in IIS it's work again.

// GET: /Account/ExternalLoginCallback
[AllowAnonymous]
public async Task<ActionResult> ExternalLoginCallback(string returnUrl)
{
    var loginInfo = await AuthenticationManager.GetExternalLoginInfoAsync();
    if (loginInfo == null)
        return RedirectToAction("Login", new { ReturnUrl = ViewBag.ReturnUrl });
    // Sign in the user with this external login provider if the user already has a login
    CustomUser user = await AppService.CustomUserStore.FindByEmailAsync(loginInfo.Email);
    if (user != null)
        await AppService.CustomUserStore.Insert(user.UserName, loginInfo.Login.LoginProvider, loginInfo.Login.ProviderKey);
    var result = await SignInManager.ExternalSignInAsync(loginInfo, isPersistent: false);
    switch (result)
    {
        case SignInStatus.Success:
            return RedirectToAction("Index", "Home");
        case SignInStatus.Failure:
        default:
            ViewBag.ReturnUrl = returnUrl;
            ViewBag.LoginProvider = loginInfo.Login.LoginProvider;
            return RedirectToAction("Login", new { ReturnUrl = ViewBag.ReturnUrl });
    }
}

Any body knows the problem, please help me solve. Thanks in advance !

Answer

You can clear the session before calling the ExternalLoginCallback method

// POST: /Account/ExternalLogin
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public ActionResult ExternalLogin(string provider, string returnUrl)
{
    // Request a redirect to the external login provider
    ControllerContext.HttpContext.Session.RemoveAll();
    return new ChallengeResult(provider, Url.Action("ExternalLoginCallback", "Account", new { ReturnUrl = returnUrl }));
}