在ASP.NET Core 1.1中配置基本身份验证中间件

MLE*_*MLE 6 asp.net-mvc asp.net-core

我试图在ASP.NET Core 1.1应用程序中的MVC服务上配置基本身份验证.我想通过在服务操作上添加一个属性(而不是允许基本的auth应用程序范围)来指示服务需要Basic Authentincation.在做了一些阅读之后,似乎采用中间件过滤器的相应方法.

我在Middleware过滤器上找到的最全面的指南就在这里

上面的帖子表明我需要创建一个Pipeline类,如下所示

public class MyPipeline  
{
    public void Configure(IApplicationBuilder applicationBuilder) 
    {
        var options = // any additional configuration

        //I changed this to use the "UseMiddleware"
        applicationBuilder.UseMiddleware<AuthenticationMiddleware>(options);
    }
}
Run Code Online (Sandbox Code Playgroud)

我还需要一个中间件类.我从这里修改了例子

public class AuthenticationMiddleware
{
    private readonly RequestDelegate _next;

    public AuthenticationMiddleware(RequestDelegate next)
    {
        _next = next;
    }

    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);

                //Here is the tricky bit
                DBAuth authenticator = new DBAuth(ConnectionString);


                if(authenticator.IsAuthorized(username, password))
                {
                    await _next.Invoke(context);
                }
                else
                {
                    context.Response.StatusCode = 401; //Unauthorized
                    return;
                }
            }
            else
            {
                // no authorization header
                context.Response.StatusCode = 401; //Unauthorized
                return;
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

问题:如何将连接字符串传递给AuthenticationMiddleware类,以便我可以检查数据库的用户名和密码?我真的想通过注入而不是在Middleware类中使用Configuration.GetConnectionString()来实现它.

从管道示例代码看起来似乎可以将选项传递给中间件类但我不确定如何修改AuthenticationMiddleware类以接受选项或实际上是什么类选项

PS:我知道基本身份验证很糟糕,但这是我给出的要求

Tse*_*eng 3

您应该能够通过修改您的Invoke方法来做到这一点

public async Task Invoke(HttpContext context)
Run Code Online (Sandbox Code Playgroud)

public async Task Invoke(HttpContext context, AppDbContext dbContext)
Run Code Online (Sandbox Code Playgroud)

或者替代地

public async Task Invoke(HttpContext context)
{
    var dbContext = context.RequestServices.GetService<AppDbContext>();
}
Run Code Online (Sandbox Code Playgroud)

并通常AppDbContext在应用程序的 Startup.cs 中注册您的

public ConfigureServices(IServiceCollection services)
{
    services.AddDbContext<AppDbContext>(config => 
    {
        config.UseXxx(...);
    });
}
Run Code Online (Sandbox Code Playgroud)