加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > asp.Net > 正文

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

发布时间:2020-12-16 03:48:04 所属栏目:asp.Net 来源:网络整理
导读:我试图在ASP.NET Core 1.1应用程序中的MVC服务上配置基本身份验证.我想通过在服务操作上添加一个属性(而不是允许基本的auth应用程序范围)来指示服务需要Basic Authentincation.在做了一些阅读之后,似乎采用中间件过滤器的相应方法. 我在Middleware过滤器上找
我试图在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(...);
    });
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读