Google身份验证间歇性地工作

时间:2016-08-24 16:17:18

标签: c# asp.net-mvc oauth google-authentication

我使用Google OAuth作为.NET Web应用程序的身份验证模式。虽然它似乎在我的机器上工作正常,但在现场环境中似乎间歇性地工作。

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

Google Developer Console

Google+ API已设置为启用:

Google+

默认的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提供商ID和密码填写在Startup.Auth.cs文件中:

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

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

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

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

1 个答案:

答案 0 :(得分:1)

通过从引用的SO答案中应用以下两个更改来解决该问题:

Startup.AuthOWIN's GetExternalLoginInfoAsync Always Returns null

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

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