.net core - 忽略Jwt中间件身份验证签名密钥

adn*_*ili 5 .net c# jwt openid-connect openiddict

我正在使用配置为使用json web令牌的openiddict:

// Add authentication
services.AddAuthentication();

// Add OpenId Connect/OAuth2
services.AddOpenIddict()
    .AddEntityFrameworkCoreStores<ApplicationDbContext>()
    .AddMvcBinders()
    .EnableTokenEndpoint("/connect/token")
    .AllowPasswordFlow()
    .AllowRefreshTokenFlow()
    .UseJsonWebTokens()      // access_token should be jwt
    // You can disable the HTTPS requirement during development or if behind a reverse proxy
    .DisableHttpsRequirement()
    // Register a new ephemeral key, that is discarded when the application
    // shuts down. Tokens signed using this key are automatically invalidated.
    // To be used during development
    .AddEphemeralSigningKey();
Run Code Online (Sandbox Code Playgroud)

我通过以下方式配置JWT中间件:

// Add Jwt middleware for authentication
var secretKey = Configuration.Get<AppOptions>().Jwt.SecretKey;
app.UseJwtBearerAuthentication(new JwtBearerOptions
{
    AutomaticAuthenticate = true,
    AutomaticChallenge = true,
    RequireHttpsMetadata = env.IsProduction(),
    Audience = Configuration.Get<AppOptions>().Jwt.Audience,
    Authority = Configuration.Get<AppOptions>().Jwt.Authority,
    TokenValidationParameters = new TokenValidationParameters
    {
        ValidateIssuerSigningKey = true,
        IssuerSigningKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(secretKey)),

        ValidateIssuer = true,
        // makes no difference seemingly being ignored
        //ValidIssuer = Configuration.Get<AppOptions>().Jwt.Authority,

        ValidateAudience = true,
        ValidAudience = Configuration.Get<AppOptions>().Jwt.Audience,

        ValidateLifetime = true,
    }
});

// Add OpedId Connect middleware
app.UseOpenIddict();
Run Code Online (Sandbox Code Playgroud)

如您所见,发行者签名密钥设置为对称密钥:

IssuerSigningKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(secretKey)),
Run Code Online (Sandbox Code Playgroud)

但创建的jwt access_tokens alg声明设置为RS256,所以似乎忽略了此设置,openiddict使用RSA私钥对从中生成的令牌进行签名

.AddEphemeralSigningKey();
Run Code Online (Sandbox Code Playgroud)

adn*_*ili 2

为了强制 openiddict 使用对称密钥,必须在 openiddict 中进行配置

 services.AddOpenIddict()
.AddEntityFrameworkCoreStores<ApplicationDbContext>()
.AddMvcBinders()
.EnableTokenEndpoint("/connect/token")
.AllowPasswordFlow()
.AllowRefreshTokenFlow()
.UseJsonWebTokens()
// You can disable the HTTPS requirement during development or if behind a reverse proxy
.DisableHttpsRequirement()

// set your symmetric key

.AddSigningKey(new SymmetricSecurityKey(Encoding.ASCII.GetBytes(Configuration.Get<AppOptions>().Jwt.SecretKey)));
Run Code Online (Sandbox Code Playgroud)