我有几种不同类型的用户(InternalUser
、Clinician
和 Patient
)可以登录我的网站,因此,对于每个类型的用户,我创建了一个继承自 ApplicationUser
的用户类。
如果登录用户访问网站的主页(https://example.com/),那么 MVC Controller 代码需要确定它是哪种类型的用户,以便它可以返回重定向到正确的“主页”页面( https://example.com/clinician , https://example.com/patient 等)。
在我看来,使用声明作为一种简单、低成本的方式来区分 Controller 中的用户类型似乎是合理的,而无需从数据库中加载当前用户。当我注册一个用户时,我添加了一个代表用户“类型”的声明:
await _userManager.AddClaimAsync("ihi:user_type", "clinician");
然后,在 Controller 中,我检查声明:
[Authorize]
public IActionResult Index()
{
if (User.HasClaim("ihi:user_type", "clinician")) return Redirect("...");
if (User.HasClaim("ihi:user_type", "patient")) return Redirect("...");
if (User.HasClaim("ihi:user_type", "internal")) return Redirect("...");
throw new InternalErrorException("Logged in user is not in a recognized user role");
}
关于这个方案我有几个问题:
- 这是一种合理的方法吗?
- 此方案(
[Authorize]
属性和我的声明检查)依赖于查看 cookie 的值。存储在该 cookie 中的数据是否相当安全,不会被篡改? (我希望如此,否则攻击者可以修改 cookie 并利用身份系统。)
最佳答案
Is this a reasonable approach?
是的,这是一种常见的方法,因为身份 cookie 中包含所有声明。
Is the data stored in that cookie reasonably safe from tampering?
来自 the docs :
SignInAsync creates an encrypted cookie and adds it to the current response. If you don't specify an AuthenticationScheme, the default scheme is used.
Under the covers, the encryption used is ASP.NET Core's Data Protection system.
如你所见here ,您可以对数据保护系统进行许多配置,包括使用证书创建/保护用于加密身份 cookie 的 key ,以及使用临时 key 以便在关闭应用程序时所有 cookie 永远丢失。
总的来说,除非您需要一些高级别的安全性,否则默认设置就足够了。
关于c# - ASP.NET Core 声明是否可靠且安全,不会被篡改?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53127395/