-
The issue is somewhat peculiar. It has come to my attention that utilizing IConfigureOptions doesn't yield the desired results. However, upon switching to IConfigureNamedOptions, the functionality is achieved as intended. // This works
public class JwtOptionsSetup : IConfigureNamedOptions<JwtBearerOptions>
{
private readonly JwtOptions _options;
public JwtOptionsSetup(IOptions<JwtOptions> options)
{
_options = options.Value;
}
public void Configure(JwtBearerOptions options)
{
options.TokenValidationParameters = new()
{
ValidateIssuer = true,
ValidateAudience = true,
ValidateLifetime = true,
ValidateIssuerSigningKey = true,
ValidIssuer = _options.Issuer,
ValidAudience = _options.Audience,
IssuerSigningKey = _options.EncodedSecret,
};
}
public void Configure(string? name, JwtBearerOptions options)
{
Configure(options);
}
}
// This doesn't work
public class JwtOptionsSetup : IConfigureOptions<JwtBearerOptions>
{
private readonly JwtOptions _options;
public JwtOptionsSetup(IOptions<JwtOptions> options)
{
_options = options.Value;
}
public void Configure(JwtBearerOptions options)
{
options.TokenValidationParameters = new()
{
ValidateIssuer = true,
ValidateAudience = true,
ValidateLifetime = true,
ValidateIssuerSigningKey = true,
ValidIssuer = _options.Issuer,
ValidAudience = _options.Audience,
IssuerSigningKey = _options.EncodedSecret,
};
}
}
// Pipeline code
services.AddOptions<JwtOptions>()
.Bind(configuration.GetRequiredSection(JwtOptions.SectionName))
.ValidateDataAnnotations()
.ValidateOnStart();
services.ConfigureOptions<JwtOptionsSetup>();
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme).AddJwtBearer(); After reviewing the source code of the options library for a while, it appears that this specific line is responsible for the observed behavior. In this case, the name is explicitly configured as "Bearer," causing it to deviate from the default name of string.Empty. Alternatively, using the IConfigureNamedOptions would yield the desired outcome... Can you help me understand why this happens? |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment
-
Duplicates #50274, so I'm closing this one here. |
Beta Was this translation helpful? Give feedback.
Duplicates #50274, so I'm closing this one here.