AddScheme() doesn't configure options
- Dominant language
- C#
- Stars
- 38.4k
- Forks
- 10.9k
- Avg merge
- 2d 6h
- Merged PRs (30d)
- 290
Description
### Is there an existing issue for this?
- [X] I have searched the existing issues
### Describe the bug
I'm having the same problem reported in #17539. The `AddScheme(String, Action)` method is not setting the options' values.
```cs
public class ApiKeyAuthenticationOptions : AuthenticationSchemeOptions
{
public string ApiKey { get; set; } = null!;
}
```
```cs
public class ApiKeyAuthenticationHandler : AuthenticationHandler
{
public ApiKeyAuthenticationHandler(IOptionsMonitor options,
ILoggerFactory logger,
UrlEncoder encoder) : base(options, logger, encoder)
{
if (Options.ApiKey == null) throw new ArgumentNullException(nameof(Options.ApiKey)); // NullReferenceException
}
protected override async Task HandleAuthenticateAsync()
{
// Validate API key
if (!Request.Headers.TryGetValue("x-api-key", out var key)) return AuthenticateResult.Fail("Missing API key");
if (key != Options.ApiKey) return AuthenticateResult.Fail("Invalid API key");
return AuthenticateResult.Success(new AuthenticationTicket(new ClaimsPrincipal(), Scheme.Name));
}
}
```
The handler throws a `NullReferenceException` exception with the following details
```
System.NullReferenceException: 'Object reference not set to an instance of an object.'
Microsoft.AspNetCore.Authentication.AuthenticationHandler.Options.get returned null.
```
This is how i'm configuring the scheme:
```cs
builder.Services.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = ApiKeyAuthenticationDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = ApiKeyAuthenticationDefaults.AuthenticationScheme;
})
.AddScheme(ApiKeyAuthenticationDefaults.AuthenticationScheme, options =>
{
options.ApiKey = configuration["ApiKey"] ?? throw new Exception("No API key was configured");
});
```
I even tried another approach which follows:
```cs
builder.Services.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = ApiKeyAuthenticationDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = ApiKeyAuthenticationDefaults.AuthenticationScheme;
})
.AddScheme(ApiKeyAuthenticationDefaults.AuthenticationScheme, _ => { });
builder.Services.Configure(options =>
{
options.ApiKey = configuration["ApiKey"] ?? throw new Exception("No API key was configured");
});
```
However there's no change in the error.
Of course both the previous configuration code blocks are followed by
```cs
app.UseAuthentication();
app.UseAuthorization();
```
I'm sure `configuration["ApiKey"]` is not null as its logged value is correct.
### Expected Behavior
I expect the `AddScheme()` method to set options values.
### Steps To Reproduce
_No response_
### Exceptions (if any)
_No response_
### .NET Version
8.0.400
### Anything else?
_No response_
Contributor guide
Assessment
This issue has not been assessed yet.