I have a microservice which accepts requests from different clients for which it uses different accesstoken to authenticate each client.
To do this I have created an AccessTokenAuthenticationHandler
which implements the AuthenticationHandler<AccessTokenAuthenticationOptions>
interface.
The AccessTokenAuthenticationOptions
looks like this:
public class AccessTokenAuthenticationOptions : AuthenticationSchemeOptions
{
public string AccessToken { get; set; }
}
In my StartUp.cs
I use the following code to configure the different types of authentication:
services.AddAuthentication(options =>
{
options.DefaultScheme = SchemesNamesConst.TokenAuthenticationDefaultScheme;
})
.AddScheme<AccessTokenAuthenticationOptions, AccessTokenAuthenticationHandler>(
SchemesNamesConst.TokenAuthenticationClientOneScheme, o =>
{
o.AccessToken = _clientOneAuthenticationSettings.AccessToken;
})
.AddScheme<AccessTokenAuthenticationOptions, AccessTokenAuthenticationHandler>(
SchemesNamesConst.TokenAuthenticationClientTwoScheme, o =>
{
o.AccessToken = _clientTwoAuthenticationSettings.AccessToken;
});
Above each controller that I want to authenticate the requests for ClientOne
I have added the following attribute:
[Authorize(AuthenticationSchemes = SchemesNamesConst.TokenAuthenticationClientOneScheme)]
In my AccessTokenAuthenticationHandler
I fetch the accesstoken from the HttpHeader and compare it to AccessToken
in the injected OptionsMonitor
:
public class AccessTokenAuthenticationHandler : AuthenticationHandler<AccessTokenAuthenticationOptions>
{
public AccessTokenAuthenticationHandler(IOptionsMonitor<AccessTokenAuthenticationOptions> options, ILoggerFactory logger, UrlEncoder encoder, ISystemClock clock) : base(options, logger, encoder, clock)
{
}
protected override Task<AuthenticateResult> HandleAuthenticateAsync()
{
var headers = Request.Headers;
if (!headers.TryGetValue("X-Auth-Token", out var headerToken)
|| string.IsNullOrEmpty(headerToken))
{
return Task.FromResult (AuthenticateResult.Fail ("Token not found"));
}
string accessToken = OptionsMonitor.CurrentValue.AccessToken; //AccessToken is null
if (string.IsNullOrWhiteSpace(accessToken))
{
return Task.FromResult (AuthenticateResult.Fail ("Token not defined"));
}
//Some more code to compare the two token and handle it accordingly
}
}
The problem is that at runtime OptionsMonitor.CurrentValue.AccessToken
is always null
.
What am I doing wrong?