Search code examples
c#.netjwtopenid-connectopeniddict

.net core - Jwt middleware authentication signing key being ignored


I am using openiddict which is configured to to use json web tokens:

// 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();

I have configured by JWT middleware in following manner:

// 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();

As you can see the issuer signing key is set to a symmetric key:

IssuerSigningKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(secretKey)),

but the jwt access_tokens created have alg claim set to RS256, so it seems this setting is ignored and openiddict uses the RSA private key to sign the token generated from

.AddEphemeralSigningKey();

Solution

  • In order to force the openiddict to use symmetric key it has to be configured in 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)));