我试图在ASP.NET Core 1.1应用程序中的MVC服务上配置基本身份验证.我想通过在服务操作上添加一个属性(而不是允许基本的auth应用程序范围)来指示服务需要Basic Authentincation.在做了一些阅读之后,似乎采用中间件过滤器的相应方法.
我在Middleware过滤器上找到的最全面的指南是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类,以便我可以检查数据库的用户名和密码?我真的想通过注入而不是在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(...); }); }
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。