.net core 为什么JwtHeader不提供同时接受SigningCredentials和EncryptingCredentials的构造函数?

.net core 为什么JwtHeader不提供同时接受SigningCredentials和EncryptingCredentials的构造函数?,.net-core,cryptography,jwt,.net Core,Cryptography,Jwt,我正在尝试使用System.IdentityModel.Tokens.JWT nuget包(版本5.4.0)构建JWT令牌。它符合.net标准2.0,我在项目中使用.net core 2.2 在System.IdentityModel.Tokens.Jwt命名空间下,我可以找到以下方法: public virtual JwtSecurityToken CreateJwtSecurityToken(string issuer, string audience, ClaimsIdentity sub

我正在尝试使用System.IdentityModel.Tokens.JWT nuget包(版本5.4.0)构建JWT令牌。它符合.net标准2.0,我在项目中使用.net core 2.2

在System.IdentityModel.Tokens.Jwt命名空间下,我可以找到以下方法:

public virtual JwtSecurityToken CreateJwtSecurityToken(string issuer, string audience, ClaimsIdentity subject, DateTime? notBefore, DateTime? expires, DateTime? issuedAt, SigningCredentials signingCredentials, EncryptingCredentials encryptingCredentials);
我可以使用此方法同时提供SigningCredentials和EncryptingCredentials。但是,我想使用以下代码(用于更精细的控制)来创建json字符串

var header = new JwtHeader(...);
var payload = new JwtPayload(...);
var t = new JwtSecurityToken(header, payload);

var handler = new JwtSecurityTokenHandler();

var json = handler.WriteToken(t);
令我惊讶的是,我发现JwtHeader并没有提供同时接受SigningCredentials和EncryptingCredentials的构造函数。所有施工人员如下所示:

public JwtHeader();
public JwtHeader(SigningCredentials signingCredentials);
public JwtHeader(EncryptingCredentials encryptingCredentials);
public JwtHeader(SigningCredentials signingCredentials, IDictionary<string, string> outboundAlgorithmMap);
public JwtHeader(EncryptingCredentials encryptingCredentials, IDictionary<string, string> outboundAlgorithmMap);
publicjwtheader();
公共JwtHeader(签名凭证签名凭证);
公共JwtHeader(EncryptingCredentials EncryptingCredentials);
公共JwtHeader(SigningCredentials SigningCredentials,IDictionary outboundAlgorithmMap);
公共JwtHeader(EncryptingCredentials EncryptingCredentials,IDictionary outboundAlgorithmMap);

JwtHeader不提供同时接受这两者的构造函数有什么原因吗?我在这里遗漏了什么吗?

我明白了为什么JwtHeader不提供同时接受签名凭据和加密凭据的构造函数。在任何给定时间,JwtHeader可以是JWS(JSON Web签名)令牌或JWE(JSON Web加密)令牌。这不可能同时是两者。如果您希望先签名然后加密,那么外部JWT将表示嵌套令牌类型为JWS的JWE。如果您想要加密然后签名,外部JWT将表示嵌套令牌类型为JWE的JWS

如果需要验证先签名然后加密的令牌,可以使用JwtSecurityTokenHandler.ValidateToken方法同时使用SigningCredentials和EncryptingCredentials进行一次性验证

但是,如果需要验证先加密后签名的令牌,则必须使用JwtSecurityTokenHandler.ValidateToken方法两次

  • 首先,仅使用SigningCredentials验证签名以检索加密信息(通常以声明的形式)
  • 接下来,您必须再次使用JwtSecurityTokenHandler.ValidateToken,这次只使用EncryptingCredentials,但提供加密的令牌字符串(从上一步检索)
  • 这就是为什么JwtSecurityTokenHandler可以同时接受SigningCredentials和EncryptingCredentials,而JwtHeader不能

    如果有一些关于如何正确使用这个API的文档就好了。我想我们必须阅读JWT、JWS和JWE的标准

    • (JWT)

    • (JWS)

    • (JWE)


    我假设您不能对一条消息进行签名和加密。您可以加密一条消息,然后将其包装在另一条已签名的消息中;或者反过来说。但因为这是两条消息,所以它将是两个不同的头。(所有假设,实际上不熟悉JWT或此库的对象模型)