我正在尝试在 ASP.NET Core 1.1 应用程序中的 MVC 服务上配置基本身份验证。我想通过在服务操作上添加一个属性来指示服务需要基本身份验证(而不是允许基本身份验证应用程序范围)。在阅读了一些内容后,似乎合适的方法是使用中间件过滤器。
我在中间件过滤器上找到的最全面的指南在这里
上面的帖子指出我需要创建一个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);
}
}
我还需要一个中间件类。我已经从这里修改了和示例
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类,以便根据数据库检查用户名和密码?我真的想通过注入来实现,而不是在中间件类中使用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(...);
});
}