ASP.NET对ClaimTypes的要求

ASP.NET requirements for ClaimTypes

我正在研究在ASP.NET(MVC Core 1.0)中使用基于声明的授权。设置ClaimsIdentity时,我提供了一个键/值字符串对列表,以表示每个Claim。例:

1
2
3
4
5
6
List<Claim> claims = new List<Claim>
{
    new Claim("UserID", user.ID),
    new Claim("Name", user.Name),
    new Claim("Role","basic")
};

我的理解是,我可以使用任何想要的键/值。但是我注意到通过ClaimsType类可以使用一些预定义的键。因此,我可能会使用其中一些预定义的键来代替:

1
2
3
4
5
6
List<Claim> claims = new List<Claim>
{
    new Claim(ClaimTypes.Sid, user.ID),
    new Claim(ClaimTypes.Name, user.Name),
    new Claim(ClaimTypes.Role,"basic")
};

问题:

  • 如果我使用预定义的键,关于分配给每个键的实际值是否有任何规则/限制,或者是由应用程序定义的?例如,是否可以将数据库主键粘贴在ClaimTypes.Sid中,还是ASP.NET对ClaimTypes.Sid应该包含哪些内容有某些期望?

  • 是否需要任何ClaimTypes,还是完全由应用程序来决定要包含或不包含的内容?我想答案可能取决于我将要与之交互的特定第三方身份验证服务,但是一个不使用任何第三方身份验证的独立ASP.NET项目的简单情况又如何呢? ASP.NET本身有什么要求吗?

  • 任何与使用特定键/值有关的要求和/或最佳实践的链接都将受到赞赏。


    If I use the pre-defined keys, are there any rules/restrictions
    regarding the actual values assigned to each key, or is it application
    defined? For example, is it OK to stick a database primary key in
    ClaimTypes.Sid, or does ASP.NET have certain expectations of what
    ClaimTypes.Sid should contain?

    如果得到的Claim,则使用预定义的ClaimTypes之一还将修改Type属性。您可以在此处找到这些类型的列表。据我所知,您可以自由地将数据库ID放入ClaimTypes.Sid,但是我强烈建议您使用自己的名称来命名它。

    Are there any ClaimTypes that are required, or is it completely up to
    the application to decide what to include or not include? I imagine
    the answer may depend on specific third-party authentication services
    I would interact with, but how about the simple case of a
    self-contained ASP.NET project that does not use any third-party
    authentication. Does ASP.NET itself have any requirements?

    假设没有第三方,您可以决定什么是必需的,什么不是必需的。请记住,如果您将声明存储在Cookie(不是第三方来源)中,则空间会有所限制; Cookie的总数不能超过4096个字节。

    到目前为止,我在这里找到关于ASP.NET Core声明身份验证的最佳文章。到发布时,我们仍在RC1中,因此某些详细信息可能会在最终版本之前更改。


  • If I use the pre-defined keys, are there any rules/restrictions regarding the actual values assigned to each key, or is it application defined? For example, is it OK to stick a database primary key in ClaimTypes.Sid, or does ASP.NET have certain expectations of what ClaimTypes.Sid should contain?
  • 基本上没有规则限制,但是它取决于令牌的使用者。默认情况下,Asp.Net Identity期望用户名为ClaimTypes.Name(用户显示名称或邮件,无论您使用什么),角色为ClaimTypes.Role和用户ID(不必为行ID,仅用于标识用户即是) Guid或电子邮件地址)为ClaimTypes.NameIdentifier。默认值也可以在GitHub上看到。

    话虽如此,如果您使用自定义声明类型,则在配置Asp.Net Identity时需要在ClaimsIdentityOptions中进行说明。

    User.Identity.Name中设置的声明类型是在控制器中执行User.Identity.Name访问它时使用的声明类型。如果您的声明类型与ClaimsIdentityOptions中的声明类型不匹配,它将仅返回null。