我正在使用AspNet Core构建Web api和JWT令牌来验证用户身份。
我看到在TokenValidationParameters
中,ValidateIssuerSigningKey
属性的默认值为false。
当使用 HMAC256 对称密钥签名和验证令牌时(如果没有像RSA那样向令牌添加任何公钥),如果将其设置为true,是否有任何区别? )?
services
.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddJwtBearer(cfg =>
{
cfg.RequireHttpsMetadata = false;
cfg.SaveToken = true;
string jwtIssuer = configuration["JwtIssuer"];
SymmetricSecurityKey securityKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(configuration["JwtKey"]));
cfg.TokenValidationParameters = new TokenValidationParameters
{
ValidIssuer = jwtIssuer,
ValidAudience = jwtIssuer,
ValidateIssuerSigningKey = true,
IssuerSigningKey = securityKey,
ClockSkew = TimeSpan.Zero
};
});
还是仅在使用RSA密钥时才需要将ValidateIssuerSigningKey
设置为true?
以下是此属性的代码级文档:
//
// Summary:
// Gets or sets a boolean that controls if validation of the Microsoft.IdentityModel.Tokens.SecurityKey
// that signed the securityToken is called.
//
// Remarks:
// It is possible for tokens to contain the public key needed to check the signature.
// For example, X509Data can be hydrated into an X509Certificate, which can be used
// to validate the signature. In these cases it is important to validate the SigningKey
// that was used to validate the signature.
[DefaultValue(false)]
public bool ValidateIssuerSigningKey { get; set; }
答案 0 :(得分:0)
基于查看Microsoft.IdentityModel.Tokens源代码,我只能在这里找到使用ValidateIssuerSigningKey布尔属性的一个地方,
最终导致该代码块被执行:
X509SecurityKey x509SecurityKey = securityKey as X509SecurityKey;
if (x509SecurityKey?.Certificate is X509Certificate2 cert)
{
DateTime utcNow = DateTime.UtcNow;
var notBeforeUtc = cert.NotBefore.ToUniversalTime();
var notAfterUtc = cert.NotAfter.ToUniversalTime();
if (notBeforeUtc > DateTimeUtil.Add(utcNow, validationParameters.ClockSkew))
throw LogHelper.LogExceptionMessage(new SecurityTokenInvalidSigningKeyException(LogHelper.FormatInvariant(LogMessages.IDX10248, notBeforeUtc, utcNow)));
LogHelper.LogInformation(LogMessages.IDX10250, notBeforeUtc, utcNow);
if (notAfterUtc < DateTimeUtil.Add(utcNow, validationParameters.ClockSkew.Negate()))
throw LogHelper.LogExceptionMessage(new SecurityTokenInvalidSigningKeyException(LogHelper.FormatInvariant(LogMessages.IDX10249, notAfterUtc, utcNow)));
LogHelper.LogInformation(LogMessages.IDX10251, notAfterUtc, utcNow);
}
即该标志仅与X509证书有关,并且仅对X509证书有效期进行测试。因此,我怀疑它不会影响使用HMAC256验证的令牌……除非从X509证书获得了HMAC密钥!