[英]Request had invalid authentication credentials. Expected OAuth 2 access token, login cookie or other valid authentication credential
[英]How to remove access to site when the user had a previously valid cookie?
用户可以访问.net MVC OWIN身份验证的网站,并具有将其登录的Cookie。然后,管理员撤消访问并将其角色重置为“无访问权”角色。
网站如何检测到这一点? 登录后能否更新Cookie身份验证代码以仅检查数据库中用户的角色? 如果是这样,有人可以指出正确的方向来覆盖此功能吗?
更新:
我相信OWIN Startup类中的以下代码是需要更新的内容,以拦截/替代cookie的身份验证。 我想做的是检查用户是否有权访问该网站(如果该用户是“无访问权限”角色的一部分,请拒绝他们的登录)。
public partial class Startup
{
public void ConfigureAuthentication(IAppBuilder app)
{
app.UseCookieAuthentication(new CookieAuthenticationOptions
{
AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
LoginPath = new PathString("/Login"),
Provider = new CookieAuthenticationProvider
{
OnValidateIdentity = context =>
{
//Somehow check the users role here?
}
}
});
}
}
这是我最终所做的事情,似乎可以按照我认为的方式工作。 读取OWIN cookie时,我检查了用户数据库(我意识到这是多余的),以确保未撤消他们的访问。 如果它已被撤消,我将拒绝cookie身份验证,并将它们发送回站点登录屏幕。
public partial class Startup
{
public void ConfigureAuthentication(IAppBuilder app)
{
app.UseCookieAuthentication(new CookieAuthenticationOptions
{
AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
LoginPath = new PathString("/Login"),
Provider = new CookieAuthenticationProvider()
{
OnValidateIdentity = context =>
{
string userName = context.Identity.Name;
User user = userRepository.Users.SingleOrDefault(u => u.UserName == userName);
if(user.Roles.SingleOrDefault(r => r.Name == "No Access") != null)
{
context.RejectIdentity();
}
return System.Threading.Tasks.Task.FromResult(0);
}
}
});
}
}
从我的测试来看,这似乎可行。 我认为可能有一个更好的,较少冗余的解决方案,但是我没有遇到。 我相信这段代码会在每次页面加载时运行,这让我有些担心。 稍后我可能会发布另一个问题,询问是否有更好的方法可以执行此操作,但是目前为止,此方法可行。
马克C的回应确实帮助我量身定制了关于该主题的搜索,谢谢。
最简单的解决方案是“删除”用户的cookie,以便注销它们。 然后,当他们再次登录时,他们将拥有新的权限。
我之所以说“删除”,是因为您实际上并没有删除Cookie,而是使其无效-通常通过设置其过去的日期为佳。
来自MSDN的此代码会将cookie的过期日期设置为过去的一天:
if (Request.Cookies["UserSettings"] != null)
{
HttpCookie myCookie = new HttpCookie("UserSettings");
myCookie.Expires = DateTime.Now.AddDays(-1d);
Response.Cookies.Add(myCookie);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.