我已覆盖 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 部分提供。
我怀疑让您的 ApplicationDbContext
从 DbContext
继承而不是从 IdentityDbContext
继承是安全的 - 这将消除任何命中的可能性缺少您不需要的表。接下来,您可以删除 ApplicationUserManager
(因为它需要 IdentityDbContext
)。
我已经blogged关于使用 AD 作为设置 OWIN cookie 的服务 - 其中一些可能对您有用。
关于c# - Owin 授权超时后 EF 抛出 AspNetUsers 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43896706/