启动应用触发IDX10703错误:无法创建对称安全密钥
问题:应用启动失败,抛出JWT认证错误IDX10703
错误信息
System.ArgumentException: IDX10703: Cannot create symmetric security key. Key length is zero. at Microsoft.IdentityModel.Tokens.SymmetricSecurityKey..ctor(Byte[] key) in C:\agent2\_work\56\s\src\Microsoft.IdentityModel.Tokens\SymmetricSecurityKey.cs:line 51 at TestCentral.Web.Startup.AuthConfigurer.<>c__DisplayClass0_0.<Configure>b__0(JwtBearerOptions options) in C:\Users\Kamal Aliyu\Desktop\Central EPMS\src\TestCentral.Web.Mvc\Startup\AuthConfigurer.cs:line 20 at Microsoft.Extensions.Options.OptionsFactory`1.Create(String name)
报错代码片段
{ if (bool.Parse(configuration["Authentication:JwtBearer:IsEnabled"])) { services.AddAuthentication() .AddJwtBearer(options => { options.Audience = configuration["Authentication:JwtBearer:Audience"]; options.TokenValidationParameters = new TokenValidationParameters { // The signing key must match! ValidateIssuerSigningKey = true, IssuerSigningKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(configuration["Authentication:JwtBearer:SecurityKey"])), // Validate the JWT Issuer (iss) claim ValidateIssuer = true, ValidIssuer = configuration["Authentication:JwtBearer:Issuer"], // Validate the JWT Audience (aud) claim ValidateAudience = true, ValidAudience = configuration["Authentication:JwtBearer:Audience"], // Validate the token expiry ValidateLifetime = true, // If you want to allow a certain amount of clock drift, set that here ClockSkew = TimeSpan.Zero }; }); } }
原因与解决方案
核心原因
configuration["Authentication:JwtBearer:SecurityKey"]返回空字符串或null,调用Encoding.ASCII.GetBytes后得到长度为0的字节数组,而SymmetricSecurityKey构造函数不允许传入空字节数组,因此触发异常。
解决步骤
- 检查配置项:确认配置文件(如appsettings.json)、环境变量或配置中心中,
Authentication:JwtBearer:SecurityKey已设置合法值。注意对称加密密钥需满足长度要求:比如使用HS256算法时,密钥长度至少为32字节(对应明文至少32个ASCII字符,或匹配长度的Base64编码值)。 - 排查配置加载问题:若之前运行正常,可能是部署时配置被覆盖、环境变量缺失,或是配置文件未正确同步到目标环境。
- 添加空值校验:在代码中增加前置校验,提前暴露配置问题,避免到构造密钥时才报错:
var securityKey = configuration["Authentication:JwtBearer:SecurityKey"]; if (string.IsNullOrWhiteSpace(securityKey)) { throw new InvalidOperationException("JWT认证配置项SecurityKey未设置或为空"); } options.TokenValidationParameters = new TokenValidationParameters { ValidateIssuerSigningKey = true, IssuerSigningKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(securityKey)), // 其他配置项保持不变 };
内容的提问来源于stack exchange,提问作者kamal Aliyu
相关产品推荐
相关产品推荐

