How to correctly get dependent scoped services from ISecurityTokenValidator

后端 未结 1 356
盖世英雄少女心
盖世英雄少女心 2020-12-03 22:59

In my asp.net core 2.0 web app, I\'ve got a custom ISecurityTokenValidator which validates tokens.

It depends on a repository to do a db lookup - the re

相关标签:
1条回答
  • 2020-12-03 23:44

    Old question but the best way I have found to solve this problem is to use IPostConfigureOptions<JwtBearerOptions> to configure SecurityTokenValidators.

    First register the JWT bearer and options

            services.AddAuthentication(options =>
            {
                ...
            }).AddJwtBearer(AuthenticateScheme, options =>
            {
                options.TokenValidationParameters = new TokenValidationParameters
                {
                    ...
                };
            });
    

    Then register a custom implementation of IPostConfigureOptions<JwtBearerOptions>

        services.AddSingleton<IPostConfigureOptions<JwtBearerOptions>, CustomJwtBearerOptionsPostConfigureOptions>();
    

    And register a custom implementation of ISecurityTokenValidator

        services.AddSingleton<MyCustomSecurityTokenValidator>();
    

    CustomJwtBearerOptionsPostConfigureOptions could look something like:

    public class CustomJwtBearerOptionsPostConfigureOptions : IPostConfigureOptions<JwtBearerOptions>
    {
        private readonly MyCustomSecurityTokenValidator _tokenValidator; //example dependancy
    
        public CustomJwtBearerOptionsPostConfigureOptions(MyCustomSecurityTokenValidator tokenValidator)
        {
            _tokenValidator = tokenValidator;
        }
    
        public void PostConfigure(string name, JwtBearerOptions options)
        {
            options.SecurityTokenValidators.Clear();
            options.SecurityTokenValidators.Add(_tokenValidator);
        }
    }
    

    Now options.SecurityTokenValidators is configured by CustomJwtBearerOptionsPostConfigureOptions which is instantiated by dependency injection and can pass on the relevant decencies.

    0 讨论(0)
提交回复
热议问题