如何使用AuthenticationMiddleware并注入应用程序设置

问题描述 投票:1回答:1

我试过这个例子:https://www.danylkoweb.com/Blog/no-configurationmanager-in-aspnet-core-GC

没有运气。

它编译但是,我的设置不会回来。该链接表示json文件应位于Configuration文件夹中。

还有另一种方法吗?

只是尝试在设置文件中设置连接字符串。

{
  "Settings": {
    "ConnectionString": "Data Source=XXXXXXXXXXXXXXXXXXXXXXXXXX"
  }
}

public class Settings
{
    public string ConnectionString { get; set; }
}


    public class Startup
    {
        private Settings _settings;

        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc();//.SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
            //services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);

            // Added - uses IOptions<T> for your settings.
            services.AddOptions();

            // Added - Confirms that we have a home for our DemoSettings
            services.Configure<Settings>(Configuration.GetSection("Settings"));
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseHsts();
            }

            app.UseMiddleware<AuthenticationMiddleware<IOptions<Settings>>>();
            app.UseHttpsRedirection();
            app.UseMvc();
        }
    }
}

和中间件

public class AuthenticationMiddleware<TOptions>
{
    private readonly RequestDelegate _next;
    private Settings _settings;

    /// <summary>
    /// 
    /// </summary>
    /// <param name="settings"></param>
    /// <param name="next"></param>
    public AuthenticationMiddleware(IOptions<Settings> settings, RequestDelegate next)
    {
        _next = next;
        _settings = settings.Value;
    }

    public async Task Invoke(HttpContext context)
    {
        string authHeader = context.Request.Headers["Authorization"];
        if (authHeader != null && authHeader.StartsWith("Basic"))
        {
            //Extract credentials
            string encodedUsernamePassword = authHeader.Substring("Basic ".Length).Trim();
            Encoding encoding = Encoding.GetEncoding("iso-8859-1");
            string usernamePassword = encoding.GetString(Convert.FromBase64String(encodedUsernamePassword));

            int seperatorIndex = usernamePassword.IndexOf(':');

            var username = usernamePassword.Substring(0, seperatorIndex);
            var password = usernamePassword.Substring(seperatorIndex + 1);

            if (username == "test" && password == "test")
            {
                await _next.Invoke(context);
            }
            else
            {
                context.Response.StatusCode = 401; //Unauthorized
                return;
            }
        }
        else
        {
            // no authorization header
            context.Response.StatusCode = 401; //Unauthorized
            return;
        }
    }
}
c# asp.net-core-webapi
1个回答
0
投票

要在Settings中使用AuthenticationMiddleware,您可以尝试以下方法:

  1. 将以下部分添加到appsettings.json { "Logging": { "LogLevel": { "Default": "Warning" } }, "AllowedHosts": "*", "Settings": { "ConnectionString": "Data Source=XXXXXXXXXXXXXXXXXXXXXXXXXX" } }
  2. 创建AuthenticationMiddleware public class AuthenticationMiddleware { private readonly RequestDelegate _next; private readonly Settings _settings; public AuthenticationMiddleware(RequestDelegate next, IOptions<Settings> options) { _next = next; _settings = options.Value; } public async Task InvokeAsync(HttpContext context) { //await context.Response.WriteAsync($"This is { GetType().Name }"); //decide whether to invoke line below based on your business logic await _next(context); } }
  3. 注册AuthenticationMiddlewareSettings //Configure Settings services.Configure<Settings>(Configuration.GetSection("Settings")); //Configure middleware app.UseMiddleware<AuthenticationMiddleware>();
© www.soinside.com 2019 - 2024. All rights reserved.