Custom Authentication scheme IOptionsMonitor not working

516 Views Asked by At

I have set up an authentication scheme. I am trying to pass on options from the startup class.

In my start up I have:

services.AddAuthentication(TokenAuthentication.SchemeName)
.AddScheme<TokenAuthenticationOptions, TokenAuthentication>
                    (TokenAuthentication.SchemeName, o => {
                        o.AuthQueryKey = "jwt";
                    });

In my scheme class I have the following constructor:

    public TokenAuthentication(IOptionsMonitor<TokenAuthenticationOptions> options, ILoggerFactory logger, 
                                UrlEncoder encoder, ISystemClock clock, LoginManager loginManager) 
                                    : base(options, logger, encoder, clock)
    {
        this.options = options;
        this.loginManager = loginManager;
    }

Inside the HandleAuthenticateAsync I am trying to access the options like this:

var options = this.options.CurrentValue;
if (options.AuthQueryKey == null) // always null

On debugger I found that the constructor runs first, then the o.AuthQueryKey = "jwt" and finally the HandleAuthenticateAsync. Why doesn't AuthQueryKey get the value "jwt"?

The reason I need to use options is since I am reusing the authentication in two projects with different attributes. My next resort is to use another singleton for options, but why isn't this lamda function setting the value?

1

There are 1 best solutions below

0
On

According to https://learn.microsoft.com/en-us/aspnet/core/fundamentals/configuration/options, I need to set the options with the Configure function.

services.Configure<TokenAuthenticationOptions>(o => {
    o.AuthQueryKey = "jwt";
});

It is still odd though that I can't figure out what the lamda inside the AddScheme function is even meant for.