我使用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提供商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>
我在ExternalLogin
和ExternalLoginCallback
方法中添加了几行代码来记录失败的位置,似乎无法调用ExternalLoginCallback
。同样,这会间歇性地发生,因为有时我能够完成登录。问题是什么?
答案 0 :(得分:1)
通过从引用的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);
}