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

标签 asp.net-mvc asp.net-core

我正在尝试在 ASP.NET Core 1.1 应用程序中的 MVC 服务上配置基本身份验证。我想通过在服务操作上添加属性来指示服务需要基本身份验证(而不是允许在应用程序范围内进行基本身份验证)。经过一些阅读后,似乎执行此操作的适当方法是使用中间件过滤器。

我找到的关于中间件过滤器的最全面的指南是 here

上面的帖子表明我需要创建一个 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);
    }
}

我还需要一个中间件类。我已经修改了 here 中的示例

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

问题:如何将连接字符串传递到 AuthenticationMiddleware 类,以便我可以根据数据库检查用户名和密码?我真的想通过注入(inject)来完成此操作,而不是使用 Middleware 类中的 Configuration.GetConnectionString() 。

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

PS:我知道基本身份验证不好,但这是我的要求

最佳答案

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

public async Task Invoke(HttpContext context)

public async Task Invoke(HttpContext context, AppDbContext dbContext)

或者

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

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

public ConfigureServices(IServiceCollection services)
{
    services.AddDbContext<AppDbContext>(config => 
    {
        config.UseXxx(...);
    });
}

关于asp.net-mvc - 在 ASP.NET Core 1.1 中配置基本身份验证中间件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41643543/

相关文章:

asp.net-mvc - 如何通过 netcore3.1 中的环境变量更改 Kestrel (AspNetCore) 监听端口

asp.net - 是否可以在 ASP.NET Core API 中运行 Umbraco?

iis - .NET Core SDK未安装ASPNETCoreModule

asp.net-mvc - Url.Action 正在编码参数值

javascript - 将 Session 值从我的 MVC 应用程序获取到我的 Javascript 中

c# - ASP.Net Core 2.0 中的自动映射器

c# - 英孚。连接未关闭。连接的当前状态是 connecting

c# - 授权属性意外工作

jquery - asp.net mvc4 jquery 不工作

c# - asp.Net MVC 如何为图表中的每个条形设置颜色?