asp.net-mvc - 谷歌 aspnet mvc5 上的 AuthenticationManager.GetExternalLoginInfoAsync() 返回 null

标签 asp.net-mvc visual-studio-2015 owin google-authentication

我使用默认的 Visual Studio 2015 模板和 Google 身份验证开发了 ASPNET MVC 5 应用程序。在开发环境中一切正常,但在外部身份验证后的实际调用中 AuthenticationManager.GetExternalLoginInfoAsync()有时返回 null。

通常它会在一天的中心时间(从 08:00 到 20:00)返回 null,但我还没有找到模式,因为有时在那个时间有效。我查看了开发者控制台,但没有太多请求(过去 12 小时内有 22 个),并且全部成功。

我尝试了其他 StackOverflow 线程的一些解决方案,但它们不起作用。另外,我只能在晚上尝试它们,因为这是一个个人项目,然后连接成功,我无法重现该问题。

代码是标准的:

  • 启动时

    public void ConfigureAuth(IAppBuilder app)
    {
        // Configure the db context, user manager and signin manager to use a single instance per request
        app.CreatePerOwinContext(ApplicationDbContext.Create);
        app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create);
        app.CreatePerOwinContext<ApplicationSignInManager>(ApplicationSignInManager.Create);
    
        // Enable the application to use a cookie to store information for the signed in user
        // and to use a cookie to temporarily store information about a user logging in with a third party login provider
        // Configure the sign in cookie
        app.UseCookieAuthentication(new CookieAuthenticationOptions
        {
            AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
            LoginPath = new PathString("/Account/Login"),
            Provider = new CookieAuthenticationProvider
            {
                // Enables the application to validate the security stamp when the user logs in.
                // This is a security feature which is used when you change a password or add an external login to your account.  
                OnValidateIdentity = SecurityStampValidator.OnValidateIdentity<ApplicationUserManager, ApplicationUser>(
                    validateInterval: TimeSpan.FromMinutes(30),
                    regenerateIdentity: (manager, user) => user.GenerateUserIdentityAsync(manager))
            }
        });            
        app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);
    
        // Enables the application to temporarily store user information when they are verifying the second factor in the two-factor authentication process.
        app.UseTwoFactorSignInCookie(DefaultAuthenticationTypes.TwoFactorCookie, TimeSpan.FromMinutes(5));
    
        // Enables the application to remember the second login verification factor such as phone or email.
        // Once you check this option, your second step of verification during the login process will be remembered on the device where you logged in from.
        // This is similar to the RememberMe option when you log in.
        app.UseTwoFactorRememberBrowserCookie(DefaultAuthenticationTypes.TwoFactorRememberBrowserCookie);
    
        var google = new GoogleOAuth2AuthenticationOptions()
        {
            ClientId = "xxxx",
            ClientSecret = "xxxx",
            Provider = new GoogleOAuth2AuthenticationProvider()
        };
        google.Scope.Add("email");
        app.UseGoogleAuthentication(google);
    }
    
  • 在外部登录回调中

    //
    // GET: /Account/ExternalLoginCallback
    [AllowAnonymous]
    public async Task<ActionResult> ExternalLoginCallback(string returnUrl)
    {
        Log.Debug("AuthenticationManager.GetExternalLoginInfoAsync()");
        var loginInfo = await AuthenticationManager.GetExternalLoginInfoAsync();
        if (loginInfo == null)
        {
            Log.Error("AuthenticationManager.GetExternalLoginInfoAsync(): null");
            return RedirectToAction("Login");
        }
    ...
    

更多信息
我已经与另一个用户创建了新的 Google 凭据,当我更改 clientId 和 clientSecret 时,它会再次起作用...我什至不知道什么时候...

更多信息
问题不在于凭据,我“只”需要重新启动 ASP.NET 应用程序来解决问题,也许这个新线索可以帮助别人帮助我。

未复制
我已经发布了答案,但它不在 OWIN's GetExternalLoginInfoAsync Always Returns null 中帖子中,我提到了我找到解决方案的线程:ASP.NET_SessionId + OWIN Cookies do not send to browser

最佳答案

最后(我认为)我在一周后找到了解决方案,没有登录失败。这一切都归功于this StackOverflow thread 。我的解决方案是在 AccountController.ExternalLogin 操作中插入以下行:

Session["Workaround"] = 0;

在上面的线程(以及那里提供的链接)中,找到了混合 ASPNET MVC 和 OWIN 组件的 session 和 cookie 时出现的错误的更好解释。

完整 Controller 服务代码:

    //
    // POST: /Account/ExternalLogin
    [HttpPost]
    [AllowAnonymous]
    [ValidateAntiForgeryToken]
    public ActionResult ExternalLogin(string provider, string returnUrl)
    {
        // https://stackoverflow.com/questions/20737578/asp-net-sessionid-owin-cookies-do-not-send-to-browser
        Session["Workaround"] = 0;
        // Request a redirect to the external login provider
        return new ChallengeResult(provider, Url.Action("ExternalLoginCallback", "Account", new { ReturnUrl = returnUrl }));
    }

关于asp.net-mvc - 谷歌 aspnet mvc5 上的 AuthenticationManager.GetExternalLoginInfoAsync() 返回 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40269783/

相关文章:

asp.net-mvc - 在 ServiceStack 服务中获取请求 URL、方案、主机名和端口

node.js - 在 Visual Studio 中发布 npm 模块文件夹

MySQL 数据源未显示在 Visual Studio 2015 中

c# - OWIN 无法使用 webapp.start 单独运行多个应用程序

c# - SignalR 服务器 --> 客户端调用不工作

asp.net-mvc - 当页面依赖于 session 时,处理永久链接的正确方法是什么?

c# - 如何使用 Razor 重定向到主页

c# - NHibernate - 延迟加载原始类型

c# - 运行代码片段并呈现结果的基本 VS 扩展(类似于 watch )

sql-server - 新的 ASP.NET MVC 身份框架是否可以在没有 Entity Framework 和 SQL Server 的情况下工作?