c# - ASP.NET Core 声明是否可靠且安全,不会被篡改?

标签 c# asp.net-core asp.net-core-identity

我有几种不同类型的用户(InternalUserClinicianPatient)可以登录我的网站,因此,对于每个类型的用户,我创建了一个继承自 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");
}

关于这个方案我有几个问题:

  1. 这是一种合理的方法吗?
  2. 此方案([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/

相关文章:

c# - 在 .net 中创建安装程序

c# - 如何在 ASP.NET Core 中设置 cookie validateInterval?

c# - 如何将带小数的数字的外国字符串表示形式转换为 double ?

c# - 新授权模型中的复杂条件 (AND/OR) - ASP.NET Core?

session - 在 ASP.NET Core MVC Identity 中部署 Docker 后自动注销

c# - 为什么我的 List<child> 不能转换成 IList<parent>?

c# - 使用 Swashbuckle Aspnetcore 将 `host` 、 `basePath` 和 `schemes` 添加到 swagger.json

pinvoke - 与 ASP.net vNext 中的非托管代码进行互操作

asp.net-core - 如何获取当前的TraceId和SpanId

c# - 如何在 ASP.NET Core Identity 中注销用户