c# - Owin 授权超时后 EF 抛出 AspNetUsers 错误

标签 c# asp.net-mvc entity-framework asp.net-identity owin

我已覆盖 AccountController 中对 MVC5 应用程序的授权。它可以很好地登录和注销、获取上下文等。但是,如果授权超时,它不会将我重定向回登录页面,而是会抛出错误:

Invalid object name 'dbo.AspNetUsers'.

我在身份验证中没有使用 EF,而是使用服务,因此我没有这些表。但是,我找不到在哪里点击此代码来引发错误。

AccountController.cs:

    public async Task<ActionResult> Login(LoginViewModel model, string returnUrl)
    {
        if (!ModelState.IsValid)
        {
            return View(model);
        }

        var userRequest = new RequestObject
        {
            Name = model.Username,
            Password = model.Password
        };

        try
        {                
            var result = await client.LoginUserAsync(userRequest);

            if (result == 0)
            {
                var user = new User
                {
                    Name = model.Username
                };

                OwinSignIn(user);

                return RedirectToAction("Index", "Home");
            }
        }
        catch (Exception)
        {
            // TODO: log error
        }

        ModelState.AddModelError("", "Invalid login attempt.");
        return View(model);
    }


    private void OwinSignIn(User user, bool isPersistence = false)
    {
        var claims = new[] {
            new Claim(ClaimTypes.Name, user.Name)
        };

        var identity = new ClaimsIdentity(claims, DefaultAuthenticationTypes.ApplicationCookie);

        var result = client.GetUserRoles(userRequest);
        var roles = result.Roles.ToList();

        if (roles.Any())
        {
            var roleClaims = roles.Select(r => new Claim(ClaimTypes.Role, r.Name));
            identity.AddClaims(roleClaims);
        }

        AuthenticationManager.SignIn(new AuthenticationProperties { IsPersistent = isPersistence }, identity);
    }

同样,只有当我登录并等待授权过期时,才会发生这种情况。我不确定我还没有更新什么方法来确保它只是返回到登录页面 - 我怀疑有一些东西正在检查 session 在某处是否仍然有效,但我不知道在哪里。

谢谢。

更新:

如果我删除 OnValidateIdentity 调用,问题就会消失。我不确定这个问题是否可以解决,或者删除它是否可以......

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

最佳答案

我了解到您已经找到问题的解决方案。如果您不使用 EF 来保存用户数据,那么可以安全地从解决方案中删除大部分 Identity 包,只保留所需的 OWIN 包。

您看到这种效果的原因是因为这一点:

OnValidateIdentity =     
    SecurityStampValidator.OnValidateIdentity<ApplicationUserManager, ApplicationUser>(
                        validateInterval: TimeSpan.FromMinutes(30),
                        regenerateIdentity: (manager, user) => user.GenerateUserIdentityAsync(manager))

它每 30 分钟执行一次请求,并检查当前 cookie 是否与数据库中的数据相同。实际上是调用默认的 ApplicationUserManager ,它默认连接到 EF 中,并且默认期望 AspNetUsers 表存在。不,您在解决方案中找不到此字符串 - 该表在 IdentityDbContext 上定义,并由 Identity 的 EF 部分提供。

我怀疑让您的 ApplicationDbContextDbContext 继承而不是从 IdentityDbContext 继承是安全的 - 这将消除任何命中的可能性缺少您不需要的表。接下来,您可以删除 ApplicationUserManager (因为它需要 IdentityDbContext)。

我已经blogged关于使用 AD 作为设置 OWIN cookie 的服务 - 其中一些可能对您有用。

关于c# - Owin 授权超时后 EF 抛出 AspNetUsers 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43896706/

相关文章:

c# - 在 C# 中序列化对象时如何指定 XML 编码

C#:将初始 DayOfWeek 设置为星期一而不是星期日

json - 在 HttpConfiguration 实例中的 ASP.NET Web API 应用程序中处理 json pretty-print 参数

c# - Entity Framework 包含命令 - 左连接还是内连接?

asp.net - 部署时抛出 SecurityException

c# - 在 C# 中将列表组合转换为逗号分隔的字符串

c# - LINQ Except/Distinct仅基于少数列,不添加重复项

c# - 在 Controller 和 View 之间修改的实体

jquery - 如何运行 jQuery 加载方法

mysql - Visual Studio Ultimate 2012 RC 是否支持 MySQL 实体?