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

时间:2018-09-04 18:52:58

标签: c# asp.net-core-webapi

我尝试了以下示例: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;
        }
    }
}

1 个答案:

答案 0 :(得分: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>();