【ASP.NET Core 认证】Claims、ClaimsIdentity、ClaimsPrincipal

前言

在 ASP.NET Core沿用了ASP.NET里面的Identity组件库,负责对用户的身份进行认证。ASP.NET Core提倡的是基于声明(Claim)的认证。
基于声明的认证对认证和授权进行了明确的区分,认证用来颁发一个用户的身份标识。而授权则是通过获取身份标识中的信息,来判断该用户能做什么,不能做什么。

认证

确认执行操作的人是谁。
当用户请求后台服务时,系统首先需要知道用户是谁,是张三、李四还是匿名?确认身份的这个过程就是“身份认证”。在我们的实际生活中,通过出示自己的身份证,别人就可以快速地确认你的身份。

授权

确认操作人是否有执行该项操作的权限。
确认身份后,已经获悉了用户信息,随后来到授权阶段。在本阶段,要做的是确认用户有没有执行该项操作的权限,如有没有匿名访问权限、有没有商品查看权限、有没有编辑权限等。

Claims相关对象

  • Claim:证件单元,存储信息最小单位
  • ClaimsIdentity:相当于是一个证件
  • ClaimsPrincipal:则是证件的持有者

一个ClaimsPrincipal中可以有多个ClaimsIdentity,而一个ClaimsIdentity中可以有多个Claim。

Claim:证件单元

Claim claim = new Claim(ClaimTypes.NameIdentifier, user.Code);

ClaimsIdentity:证件

public class ClaimsIdentity:IIdentity
{
    public ClaimsIdentity(IEnumerable<Claim> claims){}    
    public virtual string Name { get; }
    public string Label { get; set; }    
    //证件类型
    public virtual string AuthenticationType { get; }
  //是否是合法的证件。
    bool IsAuthenticated { get; }
  public virtual void AddClaim(Claim claim); 
  public virtual void RemoveClaim(Claim claim); 
  public virtual void FindClaim(Claim claim); 
}

ClaimsPrincipal:证件当事人

现实生活中,一个人有多种证件,比如身份证、驾照等,你去到不同的机构需要出示不同的证件,ClaimsPrincipal就代表上面说的这个人,证件用ClaimsIdentity表示,当然得有一张证件作为主要证件(如身份证)。
在一个系统中可能同时存在多种身份验证方案,比如我们系统本身做了用户管理功能,使用最简单的cookie身份验证方案,或者使用第三方登录,微信、QQ、支付宝账号登录,通常一个身份验证方案可以产生一张证件(ClaimsIdentity)。默认情况下,用户登录时asp.net core会选择设置好的默认身份验证方案做身份验证,本质是创建一个ClaimsPrincipal,并根据当前请求创建一个证件(ClaimsIdentity),然后将此ClaimsIdentity加入到ClaimsPrincipal
当用户登录后,我们已经可以从HttpContext.User拿到当前用户,里面就包含一张或多张证件,后续的权限判断通常就依赖里面的信息,比如所属角色、所属部门,除了证件的信息我们也可以通过用户id去数据库中查询得到更多用户信息作为权限判断的依据。

public class ClaimsPrincipal:IPrincipal 
{
    public ClaimsPrincipal(IEnumerable<ClaimsIdentity> identities){}    
    //当事人的主身份证件
    public virtual IIdentity Identity { get; }    
    public virtual IEnumerable<ClaimsIdentity> Identities { get; }
  //在否属于某个角色
    bool IsInRole(string role);
  public virtual void AddIdentity(ClaimsIdentity identity); 
}

Claim标准Type

ClaimTypes

点击查看代码
public static class ClaimTypes
    {
        //
        // 摘要:
        //     The URI for a claim that specifies the actor, http://schemas.xmlsoap.org/ws/2009/09/identity/claims/actor.
        public const string Actor = "http://schemas.xmlsoap.org/ws/2009/09/identity/claims/actor";

        //
        // 摘要:
        //     The URI for a claim that specifies the anonymous user; http://schemas.xmlsoap.org/ws/2005/05/identity/claims/anonymous.
        public const string Anonymous = "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/anonymous";

        //
        // 摘要:
        //     The URI for a claim that specifies details about whether an identity is authenticated,
        //     http://schemas.xmlsoap.org/ws/2005/05/identity/claims/authenticated.
        public const string Authentication = "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/authentication";

        //
        // 摘要:
        //     The URI for a claim that specifies the instant at which an entity was authenticated;
        //     http://schemas.microsoft.com/ws/2008/06/identity/claims/authenticationinstant.
        public const string AuthenticationInstant = "http://schemas.microsoft.com/ws/2008/06/identity/claims/authenticationinstant";

        //
        // 摘要:
        //     The URI for a claim that specifies the method with which an entity was authenticated;
        //     http://schemas.microsoft.com/ws/2008/06/identity/claims/authenticationmethod.
        public const string AuthenticationMethod = "http://schemas.microsoft.com/ws/2008/06/identity/claims/authenticationmethod";

        //
        // 摘要:
        //     The URI for a claim that specifies an authorization decision on an entity; http://schemas.xmlsoap.org/ws/2005/05/identity/claims/authorizationdecision.
        public const string AuthorizationDecision = "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/authorizationdecision";

        //
        // 摘要:
        //     The URI for a claim that specifies the cookie path; http://schemas.microsoft.com/ws/2008/06/identity/claims/cookiepath.
        public const string CookiePath = "http://schemas.microsoft.com/ws/2008/06/identity/claims/cookiepath";

        //
        // 摘要:
        //     The URI for a claim that specifies the country/region in which an entity resides,
        //     http://schemas.xmlsoap.org/ws/2005/05/identity/claims/country.
        public const string Country = "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/country";

        //
        // 摘要:
        //     The URI for a claim that specifies the date of birth of an entity, http://schemas.xmlsoap.org/ws/2005/05/identity/claims/dateofbirth.
        public const string DateOfBirth = "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/dateofbirth";

        //
        // 摘要:
        //     The URI for a claim that specifies the deny-only primary group SID on an entity;
        //     http://schemas.microsoft.com/ws/2008/06/identity/claims/denyonlyprimarygroupsid.
        //     A deny-only SID denies the specified entity to a securable object.
        public const string DenyOnlyPrimaryGroupSid = "http://schemas.microsoft.com/ws/2008/06/identity/claims/denyonlyprimarygroupsid";

        //
        // 摘要:
        //     The URI for a claim that specifies the deny-only primary SID on an entity; http://schemas.microsoft.com/ws/2008/06/identity/claims/denyonlyprimarysid.
        //     A deny-only SID denies the specified entity to a securable object.
        public const string DenyOnlyPrimarySid = "http://schemas.microsoft.com/ws/2008/06/identity/claims/denyonlyprimarysid";

        //
        // 摘要:
        //     The URI for a claim that specifies a deny-only security identifier (SID) for
        //     an entity, http://schemas.xmlsoap.org/ws/2005/05/identity/claims/denyonlysid.
        //     A deny-only SID denies the specified entity to a securable object.
        public const string DenyOnlySid = "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/denyonlysid";

        //
        // 摘要:
        //     The URI for a claim that specifies the Windows deny-only group SID of the device,
        //     http://schemas.microsoft.com/ws/2008/06/identity/claims/denyonlywindowsdevicegroup.
        public const string DenyOnlyWindowsDeviceGroup = "http://schemas.microsoft.com/ws/2008/06/identity/claims/denyonlywindowsdevicegroup";

        //
        // 摘要:
        //     The URI for a claim that specifies the DNS name associated with the computer
        //     name or with the alternative name of either the subject or issuer of an X.509
        //     certificate, http://schemas.xmlsoap.org/ws/2005/05/identity/claims/dns.
        public const string Dns = "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/dns";

        //
        // 摘要:
        //     http://schemas.microsoft.com/ws/2008/06/identity/claims/dsa.
        public const string Dsa = "http://schemas.microsoft.com/ws/2008/06/identity/claims/dsa";

        //
        // 摘要:
        //     The URI for a claim that specifies the email address of an entity, http://schemas.xmlsoap.org/ws/2005/05/identity/claims/emailaddress.
        public const string Email = "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/emailaddress";

        //
        // 摘要:
        //     http://schemas.microsoft.com/ws/2008/06/identity/claims/expiration.
        public const string Expiration = "http://schemas.microsoft.com/ws/2008/06/identity/claims/expiration";

        //
        // 摘要:
        //     http://schemas.microsoft.com/ws/2008/06/identity/claims/expired.
        public const string Expired = "http://schemas.microsoft.com/ws/2008/06/identity/claims/expired";

        //
        // 摘要:
        //     The URI for a claim that specifies the gender of an entity, http://schemas.xmlsoap.org/ws/2005/05/identity/claims/gender.
        public const string Gender = "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/gender";

        //
        // 摘要:
        //     The URI for a claim that specifies the given name of an entity, http://schemas.xmlsoap.org/ws/2005/05/identity/claims/givenname.
        public const string GivenName = "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/givenname";

        //
        // 摘要:
        //     The URI for a claim that specifies the SID for the group of an entity, http://schemas.microsoft.com/ws/2008/06/identity/claims/groupsid.
        public const string GroupSid = "http://schemas.microsoft.com/ws/2008/06/identity/claims/groupsid";

        //
        // 摘要:
        //     The URI for a claim that specifies a hash value, http://schemas.xmlsoap.org/ws/2005/05/identity/claims/hash.
        public const string Hash = "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/hash";

        //
        // 摘要:
        //     The URI for a claim that specifies the home phone number of an entity, http://schemas.xmlsoap.org/ws/2005/05/identity/claims/homephone.
        public const string HomePhone = "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/homephone";

        //
        // 摘要:
        //     http://schemas.microsoft.com/ws/2008/06/identity/claims/ispersistent.
        public const string IsPersistent = "http://schemas.microsoft.com/ws/2008/06/identity/claims/ispersistent";

        //
        // 摘要:
        //     The URI for a claim that specifies the locale in which an entity resides, http://schemas.xmlsoap.org/ws/2005/05/identity/claims/locality.
        public const string Locality = "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/locality";

        //
        // 摘要:
        //     The URI for a claim that specifies the mobile phone number of an entity, http://schemas.xmlsoap.org/ws/2005/05/identity/claims/mobilephone.
        public const string MobilePhone = "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/mobilephone";

        //
        // 摘要:
        //     The URI for a claim that specifies the name of an entity, http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name.
        public const string Name = "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name";

        //
        // 摘要:
        //     The URI for a claim that specifies the name of an entity, http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier.
        public const string NameIdentifier = "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier";

        //
        // 摘要:
        //     The URI for a claim that specifies the alternative phone number of an entity,
        //     http://schemas.xmlsoap.org/ws/2005/05/identity/claims/otherphone.
        public const string OtherPhone = "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/otherphone";

        //
        // 摘要:
        //     The URI for a claim that specifies the postal code of an entity, http://schemas.xmlsoap.org/ws/2005/05/identity/claims/postalcode.
        public const string PostalCode = "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/postalcode";

        //
        // 摘要:
        //     The URI for a claim that specifies the primary group SID of an entity, http://schemas.microsoft.com/ws/2008/06/identity/claims/primarygroupsid.
        public const string PrimaryGroupSid = "http://schemas.microsoft.com/ws/2008/06/identity/claims/primarygroupsid";

        //
        // 摘要:
        //     The URI for a claim that specifies the primary SID of an entity, http://schemas.microsoft.com/ws/2008/06/identity/claims/primarysid.
        public const string PrimarySid = "http://schemas.microsoft.com/ws/2008/06/identity/claims/primarysid";

        //
        // 摘要:
        //     The URI for a claim that specifies the role of an entity, http://schemas.microsoft.com/ws/2008/06/identity/claims/role.
        public const string Role = "http://schemas.microsoft.com/ws/2008/06/identity/claims/role";

        //
        // 摘要:
        //     The URI for a claim that specifies an RSA key, http://schemas.xmlsoap.org/ws/2005/05/identity/claims/rsa.
        public const string Rsa = "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/rsa";

        //
        // 摘要:
        //     The URI for a claim that specifies a serial number, http://schemas.microsoft.com/ws/2008/06/identity/claims/serialnumber.
        public const string SerialNumber = "http://schemas.microsoft.com/ws/2008/06/identity/claims/serialnumber";

        //
        // 摘要:
        //     The URI for a claim that specifies a security identifier (SID), http://schemas.xmlsoap.org/ws/2005/05/identity/claims/sid.
        public const string Sid = "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/sid";

        //
        // 摘要:
        //     The URI for a claim that specifies a service principal name (SPN) claim, http://schemas.xmlsoap.org/ws/2005/05/identity/claims/spn.
        public const string Spn = "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/spn";

        //
        // 摘要:
        //     The URI for a claim that specifies the state or province in which an entity resides,
        //     http://schemas.xmlsoap.org/ws/2005/05/identity/claims/stateorprovince.
        public const string StateOrProvince = "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/stateorprovince";

        //
        // 摘要:
        //     The URI for a claim that specifies the street address of an entity, http://schemas.xmlsoap.org/ws/2005/05/identity/claims/streetaddress.
        public const string StreetAddress = "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/streetaddress";

        //
        // 摘要:
        //     The URI for a claim that specifies the surname of an entity, http://schemas.xmlsoap.org/ws/2005/05/identity/claims/surname.
        public const string Surname = "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/surname";

        //
        // 摘要:
        //     The URI for a claim that identifies the system entity, http://schemas.xmlsoap.org/ws/2005/05/identity/claims/system.
        public const string System = "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/system";

        //
        // 摘要:
        //     The URI for a claim that specifies a thumbprint, http://schemas.xmlsoap.org/ws/2005/05/identity/claims/thumbprint.
        //     A thumbprint is a globally unique SHA-1 hash of an X.509 certificate.
        public const string Thumbprint = "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/thumbprint";

        //
        // 摘要:
        //     The URI for a claim that specifies a user principal name (UPN), http://schemas.xmlsoap.org/ws/2005/05/identity/claims/upn.
        public const string Upn = "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/upn";

        //
        // 摘要:
        //     The URI for a claim that specifies a URI, http://schemas.xmlsoap.org/ws/2005/05/identity/claims/uri.
        public const string Uri = "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/uri";

        //
        // 摘要:
        //     The URI for a claim that specifies the user data, http://schemas.microsoft.com/ws/2008/06/identity/claims/userdata.
        public const string UserData = "http://schemas.microsoft.com/ws/2008/06/identity/claims/userdata";

        //
        // 摘要:
        //     The URI for a claim that specifies the version, http://schemas.microsoft.com/ws/2008/06/identity/claims/version.
        public const string Version = "http://schemas.microsoft.com/ws/2008/06/identity/claims/version";

        //
        // 摘要:
        //     The URI for a claim that specifies the webpage of an entity, http://schemas.xmlsoap.org/ws/2005/05/identity/claims/webpage.
        public const string Webpage = "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/webpage";

        //
        // 摘要:
        //     The URI for a claim that specifies the Windows domain account name of an entity,
        //     http://schemas.microsoft.com/ws/2008/06/identity/claims/windowsaccountname.
        public const string WindowsAccountName = "http://schemas.microsoft.com/ws/2008/06/identity/claims/windowsaccountname";

        //
        // 摘要:
        //     http://schemas.microsoft.com/ws/2008/06/identity/claims/windowsdeviceclaim.
        public const string WindowsDeviceClaim = "http://schemas.microsoft.com/ws/2008/06/identity/claims/windowsdeviceclaim";

        //
        // 摘要:
        //     The URI for a claim that specifies the Windows group SID of the device, http://schemas.microsoft.com/ws/2008/06/identity/claims/windowsdevicegroup.
        public const string WindowsDeviceGroup = "http://schemas.microsoft.com/ws/2008/06/identity/claims/windowsdevicegroup";

        //
        // 摘要:
        //     http://schemas.microsoft.com/ws/2008/06/identity/claims/windowsfqbnversion.
        public const string WindowsFqbnVersion = "http://schemas.microsoft.com/ws/2008/06/identity/claims/windowsfqbnversion";

        //
        // 摘要:
        //     http://schemas.microsoft.com/ws/2008/06/identity/claims/windowssubauthority.
        public const string WindowsSubAuthority = "http://schemas.microsoft.com/ws/2008/06/identity/claims/windowssubauthority";

        //
        // 摘要:
        //     http://schemas.microsoft.com/ws/2008/06/identity/claims/windowsuserclaim.
        public const string WindowsUserClaim = "http://schemas.microsoft.com/ws/2008/06/identity/claims/windowsuserclaim";

        //
        // 摘要:
        //     The URI for an X.500 distinguished name claim, such as the subject of an X.509
        //     Public Key Certificate or an entry identifier in a directory services Directory
        //     Information Tree; http://schemas.xmlsoap.org/ws/2005/05/identity/claims/x500distinguishedname.
        public const string X500DistinguishedName = "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/x500distinguishedname";
    }

JwtClaimTypes(推荐,简短)

ClaimTypes的type
如果要使用JwtClaimTypes,记得调用以下代码,确保ClaimType不被更改,不使用Map映射

JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear();
点击查看代码
public static class JwtClaimTypes
{
    /// <summary>Unique Identifier for the End-User at the Issuer.</summary>
    public const string Subject = "sub";

    /// <summary>End-User's full name in displayable form including all name parts, possibly including titles and suffixes, ordered according to the End-User's locale and preferences.</summary>
    public const string Name = "name";

    /// <summary>Given name(s) or first name(s) of the End-User. Note that in some cultures, people can have multiple given names; all can be present, with the names being separated by space characters.</summary>
    public const string GivenName = "given_name";

    /// <summary>Surname(s) or last name(s) of the End-User. Note that in some cultures, people can have multiple family names or no family name; all can be present, with the names being separated by space characters.</summary>
    public const string FamilyName = "family_name";

    /// <summary>Middle name(s) of the End-User. Note that in some cultures, people can have multiple middle names; all can be present, with the names being separated by space characters. Also note that in some cultures, middle names are not used.</summary>
    public const string MiddleName = "middle_name";

    /// <summary>Casual name of the End-User that may or may not be the same as the given_name. For instance, a nickname value of Mike might be returned alongside a given_name value of Michael.</summary>
    public const string NickName = "nickname";

    /// <summary>Shorthand name by which the End-User wishes to be referred to at the RP, such as janedoe or j.doe. This value MAY be any valid JSON string including special characters such as @, /, or whitespace. The relying party MUST NOT rely upon this value being unique</summary>
    /// <remarks>The RP MUST NOT rely upon this value being unique, as discussed in http://openid.net/specs/openid-connect-basic-1_0-32.html#ClaimStability </remarks>
    public const string PreferredUserName = "preferred_username";

    /// <summary>URL of the End-User's profile page. The contents of this Web page SHOULD be about the End-User.</summary>
    public const string Profile = "profile";

    /// <summary>URL of the End-User's profile picture. This URL MUST refer to an image file (for example, a PNG, JPEG, or GIF image file), rather than to a Web page containing an image.</summary>
    /// <remarks>Note that this URL SHOULD specifically reference a profile photo of the End-User suitable for displaying when describing the End-User, rather than an arbitrary photo taken by the End-User.</remarks>
    public const string Picture = "picture";

    /// <summary>URL of the End-User's Web page or blog. This Web page SHOULD contain information published by the End-User or an organization that the End-User is affiliated with.</summary>
    public const string WebSite = "website";

    /// <summary>End-User's preferred e-mail address. Its value MUST conform to the RFC 5322 [RFC5322] addr-spec syntax. The relying party MUST NOT rely upon this value being unique</summary>
    public const string Email = "email";

    /// <summary>"true" if the End-User's e-mail address has been verified; otherwise "false".</summary>
    ///  <remarks>When this Claim Value is "true", this means that the OP took affirmative steps to ensure that this e-mail address was controlled by the End-User at the time the verification was performed. The means by which an e-mail address is verified is context-specific, and dependent upon the trust framework or contractual agreements within which the parties are operating.</remarks>
    public const string EmailVerified = "email_verified";

    /// <summary>End-User's gender. Values defined by this specification are "female" and "male". Other values MAY be used when neither of the defined values are applicable.</summary>
    public const string Gender = "gender";

    /// <summary>End-User's birthday, represented as an ISO 8601:2004 [ISO8601‑2004] YYYY-MM-DD format. The year MAY be 0000, indicating that it is omitted. To represent only the year, YYYY format is allowed. Note that depending on the underlying platform's date related function, providing just year can result in varying month and day, so the implementers need to take this factor into account to correctly process the dates.</summary>
    public const string BirthDate = "birthdate";

    /// <summary>String from the time zone database (http://www.twinsun.com/tz/tz-link.htm) representing the End-User's time zone. For example, Europe/Paris or America/Los_Angeles.</summary>
    public const string ZoneInfo = "zoneinfo";

    /// <summary>End-User's locale, represented as a BCP47 [RFC5646] language tag. This is typically an ISO 639-1 Alpha-2 [ISO639‑1] language code in lowercase and an ISO 3166-1 Alpha-2 [ISO3166‑1] country code in uppercase, separated by a dash. For example, en-US or fr-CA. As a compatibility note, some implementations have used an underscore as the separator rather than a dash, for example, en_US; Relying Parties MAY choose to accept this locale syntax as well.</summary>
    public const string Locale = "locale";

    /// <summary>End-User's preferred telephone number. E.164 (https://www.itu.int/rec/T-REC-E.164/e) is RECOMMENDED as the format of this Claim, for example, +1 (425) 555-1212 or +56 (2) 687 2400. If the phone number contains an extension, it is RECOMMENDED that the extension be represented using the RFC 3966 [RFC3966] extension syntax, for example, +1 (604) 555-1234;ext=5678.</summary>
    public const string PhoneNumber = "phone_number";

    /// <summary>True if the End-User's phone number has been verified; otherwise false. When this Claim Value is true, this means that the OP took affirmative steps to ensure that this phone number was controlled by the End-User at the time the verification was performed.</summary>
    /// <remarks>The means by which a phone number is verified is context-specific, and dependent upon the trust framework or contractual agreements within which the parties are operating. When true, the phone_number Claim MUST be in E.164 format and any extensions MUST be represented in RFC 3966 format.</remarks>
    public const string PhoneNumberVerified = "phone_number_verified";

    /// <summary>End-User's preferred postal address. The value of the address member is a JSON structure containing some or all of the members defined in http://openid.net/specs/openid-connect-basic-1_0-32.html#AddressClaim </summary>
    public const string Address = "address";

    /// <summary>Audience(s) that this ID Token is intended for. It MUST contain the OAuth 2.0 client_id of the Relying Party as an audience value. It MAY also contain identifiers for other audiences. In the general case, the aud value is an array of case sensitive strings. In the common special case when there is one audience, the aud value MAY be a single case sensitive string.</summary>
    public const string Audience = "aud";

    /// <summary>Issuer Identifier for the Issuer of the response. The iss value is a case sensitive URL using the https scheme that contains scheme, host, and optionally, port number and path components and no query or fragment components.</summary>
    public const string Issuer = "iss";

    /// <summary>The time before which the JWT MUST NOT be accepted for processing, specified as the number of seconds from 1970-01-01T0:0:0Z</summary>
    public const string NotBefore = "nbf";

    /// <summary>The exp (expiration time) claim identifies the expiration time on or after which the token MUST NOT be accepted for processing, specified as the number of seconds from 1970-01-01T0:0:0Z</summary>
    public const string Expiration = "exp";

    /// <summary>Time the End-User's information was last updated. Its value is a JSON number representing the number of seconds from 1970-01-01T0:0:0Z as measured in UTC until the date/time.</summary>
    public const string UpdatedAt = "updated_at";

    /// <summary>The iat (issued at) claim identifies the time at which the JWT was issued, , specified as the number of seconds from 1970-01-01T0:0:0Z</summary>
    public const string IssuedAt = "iat";

    /// <summary>Authentication Methods References. JSON array of strings that are identifiers for authentication methods used in the authentication.</summary>
    public const string AuthenticationMethod = "amr";

    /// <summary>Session identifier. This represents a Session of an OP at an RP to a User Agent or device for a logged-in End-User. Its contents are unique to the OP and opaque to the RP.</summary>
    public const string SessionId = "sid";

    /// <summary>
    /// Authentication Context Class Reference. String specifying an Authentication Context Class Reference value that identifies the Authentication Context Class that the authentication performed satisfied. 
    /// The value "0" indicates the End-User authentication did not meet the requirements of ISO/IEC 29115 level 1. 
    /// Authentication using a long-lived browser cookie, for instance, is one example where the use of "level 0" is appropriate. 
    /// Authentications with level 0 SHOULD NOT be used to authorize access to any resource of any monetary value.
    ///  (This corresponds to the OpenID 2.0 PAPE nist_auth_level 0.) 
    /// An absolute URI or an RFC 6711 registered name SHOULD be used as the acr value; registered names MUST NOT be used with a different meaning than that which is registered. 
    /// Parties using this claim will need to agree upon the meanings of the values used, which may be context-specific. 
    /// The acr value is a case sensitive string.
    /// </summary>
    public const string AuthenticationContextClassReference = "acr";

    /// <summary>Time when the End-User authentication occurred. Its value is a JSON number representing the number of seconds from 1970-01-01T0:0:0Z as measured in UTC until the date/time. When a max_age request is made or when auth_time is requested as an Essential Claim, then this Claim is REQUIRED; otherwise, its inclusion is OPTIONAL.</summary>
    public const string AuthenticationTime = "auth_time";

    /// <summary>The party to which the ID Token was issued. If present, it MUST contain the OAuth 2.0 Client ID of this party. This Claim is only needed when the ID Token has a single audience value and that audience is different than the authorized party. It MAY be included even when the authorized party is the same as the sole audience. The azp value is a case sensitive string containing a StringOrURI value.</summary>
    public const string AuthorizedParty = "azp";

    /// <summary> Access Token hash value. Its value is the base64url encoding of the left-most half of the hash of the octets of the ASCII representation of the access_token value, where the hash algorithm used is the hash algorithm used in the alg Header Parameter of the ID Token's JOSE Header. For instance, if the alg is RS256, hash the access_token value with SHA-256, then take the left-most 128 bits and base64url encode them. The at_hash value is a case sensitive string.</summary>
    public const string AccessTokenHash = "at_hash";

    /// <summary>Code hash value. Its value is the base64url encoding of the left-most half of the hash of the octets of the ASCII representation of the code value, where the hash algorithm used is the hash algorithm used in the alg Header Parameter of the ID Token's JOSE Header. For instance, if the alg is HS512, hash the code value with SHA-512, then take the left-most 256 bits and base64url encode them. The c_hash value is a case sensitive string.</summary>
    public const string AuthorizationCodeHash = "c_hash";

    /// <summary>State hash value. Its value is the base64url encoding of the left-most half of the hash of the octets of the ASCII representation of the state value, where the hash algorithm used is the hash algorithm used in the alg Header Parameter of the ID Token's JOSE Header. For instance, if the alg is HS512, hash the code value with SHA-512, then take the left-most 256 bits and base64url encode them. The c_hash value is a case sensitive string.</summary>
    public const string StateHash = "s_hash";

    /// <summary>String value used to associate a Client session with an ID Token, and to mitigate replay attacks. The value is passed through unmodified from the Authentication Request to the ID Token. If present in the ID Token, Clients MUST verify that the nonce Claim Value is equal to the value of the nonce parameter sent in the Authentication Request. If present in the Authentication Request, Authorization Servers MUST include a nonce Claim in the ID Token with the Claim Value being the nonce value sent in the Authentication Request. Authorization Servers SHOULD perform no other processing on nonce values used. The nonce value is a case sensitive string.</summary>
    public const string Nonce = "nonce";

    /// <summary>JWT ID. A unique identifier for the token, which can be used to prevent reuse of the token. These tokens MUST only be used once, unless conditions for reuse were negotiated between the parties; any such negotiation is beyond the scope of this specification.</summary>
    public const string JwtId = "jti";

    /// <summary>Defines a set of event statements that each may add additional claims to fully describe a single logical event that has occurred.</summary>
    public const string Events = "events";

    /// <summary>OAuth 2.0 Client Identifier valid at the Authorization Server.</summary>
    public const string ClientId = "client_id";

    /// <summary>OpenID Connect requests MUST contain the "openid" scope value. If the openid scope value is not present, the behavior is entirely unspecified. Other scope values MAY be present. Scope values used that are not understood by an implementation SHOULD be ignored.</summary>
    public const string Scope = "scope";

    /// <summary>The "act" (actor) claim provides a means within a JWT to express that delegation has occurred and identify the acting party to whom authority has been delegated.The "act" claim value is a JSON object and members in the JSON object are claims that identify the actor. The claims that make up the "act" claim identify and possibly provide additional information about the actor.</summary>
    public const string Actor = "act";

    /// <summary>The "may_act" claim makes a statement that one party is authorized to become the actor and act on behalf of another party. The claim value is a JSON object and members in the JSON object are claims that identify the party that is asserted as being eligible to act for the party identified by the JWT containing the claim.</summary>
    public const string MayAct = "may_act";

    /// <summary>
    /// an identifier
    /// </summary>
    public const string Id = "id";

    /// <summary>
    /// The identity provider
    /// </summary>
    public const string IdentityProvider = "idp";

    /// <summary>
    /// The role
    /// </summary>
    public const string Role = "role";

    /// <summary>
    /// The reference token identifier
    /// </summary>
    public const string ReferenceTokenId = "reference_token_id";

    /// <summary>
    /// The confirmation
    /// </summary>
    public const string Confirmation = "cnf";

需要注意的是在创建ClaimsIdentity时需要手动指定它的NameTypeRoleType,否则它将会使用默认的ClaimTypes.NameClaimTypes.Role,这样会导致我们从ClaimsPrincipal中获取Identity.Name属性和执行IsInRole检查时失败。

var claimIdentity = new ClaimsIdentity("Cookie", JwtClaimTypes.Name, JwtClaimTypes.Role);
posted @ 2019-11-23 16:27  .Neterr  阅读(1106)  评论(0编辑  收藏  举报