Google 身份验证间歇性工作

Google Authentication working intermittently

我正在使用 Google OAuth 作为我的 .NET Web 应用程序的身份验证模式。虽然它似乎在我的机器上运行良好,但在实时环境中它似乎断断续续地工作。

以下是在开发者控制台中输入的详细信息:

并且 Google+ API 设置为启用:

默认ExternalLogin方法如下:

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

ExternalLoginCallback定义如下:

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");
}

并且 Google provider Id 和 Secret 填写在 Startup.Auth.cs 文件中:

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

我的 web.config 在 system.web 元素中包含表单身份验证:

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

我在 ExternalLoginExternalLoginCallback 方法中添加了几行代码来记录失败的地方,似乎 ExternalLoginCallback 调用失败。同样,这种情况会间歇性发生,因为有时我能够完成登录。可能是什么问题?

通过对引用的 SO 答案应用以下两个更改,问题已得到解决:

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);

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);
}