1

I am using Google OAuth as authentication mode for my .NET web application. Although it seems to be working fine on my machine, on the live environment it seems to be working intermittently.

The following are the details entered in the Developer Console:

Google Developer Console

And the Google+ API is set to be enabled:

Google+

The default ExternalLogin method is as follows:

public ActionResult ExternalLogin(string provider, string returnUrl)
{
    return new ChallengeResult(provider,
        Url.Action("ExternalLoginCallback", "Account", new { ReturnUrl = returnUrl }));
}

While the ExternalLoginCallback is defined as follows:

public async Task<ActionResult> ExternalLoginCallback(string returnUrl)
{
    var loginInfo = await AuthenticationManager.GetExternalLoginInfoAsync();
    if (loginInfo == null)
    {
        return RedirectToAction("Login");
    }

    var userEmail = loginInfo.Email;
    var loggedInUser = VerifyAndAuthenticateUser(userEmail);
    if (loggedInUser != null)
    {
        FormsAuthentication.SetAuthCookie(userEmail, false);
        return RedirectToLocal(returnUrl);
    }

    return RedirectToAction("login", "account");
}

And the Google provider Id and Secret are filled in the Startup.Auth.cs file:

app.UseGoogleAuthentication(new GoogleOAuth2AuthenticationOptions()
{
    ClientId = "xxxx",
    ClientSecret = "xxxx"
});

My web.config contains the Forms authentication in the system.web element:

<authentication mode="Forms">
  <forms loginUrl="~/account/login" timeout="2880" />
</authentication>

I've add a couple lines of code in the ExternalLogin and ExternalLoginCallback methods to log where it fails, and it seems that the ExternalLoginCallback is failed to be called. Again, this happens intermittently as sometimes I am able to complete my login. What could the issue be?

mmushtaq
  • 3,430
  • 7
  • 30
  • 47
chris05
  • 735
  • 4
  • 13
  • 27

1 Answers1

1

The issue has been solved by applying the following two changes from the referenced SO answers:

Change in Startup.Auth (OWIN's GetExternalLoginInfoAsync Always Returns null)

var google = new GoogleOAuth2AuthenticationOptions
{
    ClientId = "ClientId",
    ClientSecret = "ClientSecret",
    Provider = new GoogleOAuth2AuthenticationProvider()
};
google.Scope.Add("email");
app.UseGoogleAuthentication(google);

Change in AccountController (MVC5 Null Reference with facebook login)

public ActionResult ExternalLogin(string provider, string returnUrl)
{
    ControllerContext.HttpContext.Session.RemoveAll();
    var redirectUri = Url.Action("ExternalLoginCallback", "Account", new { ReturnUrl = returnUrl });
    return new ChallengeResult(provider, redirectUri);
}
Community
  • 1
  • 1
chris05
  • 735
  • 4
  • 13
  • 27