ASP.NET Core主机地址过滤HostFiltering

前言

在ASP.Net Core2.X调用的CreateWebHostBuilder和3.X的主要区别在于WebHost的调用,CreateDefaultBuilder被Host替换,另外一个区别是对ConfigureWebHostDefaults()的调用;html

因为新的主机生成器是通用主机生成器,所以咱们也须要知道默认Web主机配置默认配置了什么.ConfigureWebHostDefaults为咱们默认作了哪些配置?咱们一块儿来看看他为咱们默认配置的HostFiltering,HostFilteringMiddleware,其实他作的是对请求主机头的限制,也至关于一个请求主机头白名单,标识着某些主机头你能够访问,其他的你别访问了我这边未容许.json

如何使用

在这之初打算的是为给你们分享一下如何配置;算了,咱们一块儿开拓一下思惟看看他是如何作的这个中间件吧.顺便再说说当咱们使用ASP.NET Core在咱们使用中如何配置,使用主机头白名单app

services.PostConfigure<HostFilteringOptions>(options =>
{
         if (options.AllowedHosts == null || options.AllowedHosts.Count == 0)
         {
         // "AllowedHosts": "localhost;127.0.0.1;[::1]"
         var hosts = Configuration["AllowedHosts"]?.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
         // Fall back to "*" to disable.
         options.AllowedHosts = (hosts?.Length > 0 ? hosts : new[] { "*" });
  }
});

HostFilteringOptions测试

  • AllowedHosts容许访问的Host主机
  • AllowEmptyHosts是否容许请求头Host的值为空访问 默认为true
  • IncludeFailureMessage 返回错误信息,默认为true

在Configure方法中添加HostFiltering中间件ui

public void Configure(Microsoft.AspNetCore.Builder.IApplicationBuilder app, IWebHostEnvironment env)

        {
            app.UseHostFiltering();
            app.Run(context =>
            {
                return context.Response.WriteAsync("Hello World! " + context.Request.Host);
            });
        }

appsettings.jsoncode

{
  "AllowedHosts": "127.0.0.1"
}

这样就行了,那么咱们再来测试一下看看.htm

源码解析

/// <summary>
        /// Processes requests
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public  Task Invoke(HttpContext context)
        {
            var allowedHosts = EnsureConfigured();//获取容许Host集合

            if (!CheckHost(context, allowedHosts))//判断当前Host是否在容许的Host集合中
            {
                return HostValidationFailed(context);//若是不在400
            }

            return _next(context);//继续走下一个中间件
        }
        
        
        private Task HostValidationFailed(HttpContext context)
        {
            context.Response.StatusCode = 400;
            if (_options.IncludeFailureMessage)
            {
                context.Response.ContentLength = DefaultResponse.Length;
                context.Response.ContentType = "text/html";
                return context.Response.Body.WriteAsync(DefaultResponse, 0, DefaultResponse.Length);
            }
            return Task.CompletedTask;
        }
        private IList<StringSegment> EnsureConfigured()
        {
            if (_allowAnyNonEmptyHost == true || _allowedHosts?.Count > 0)//判断配置是否为空
            {
                return _allowedHosts;
            }

            return Configure();
        }
        
        
        private IList<StringSegment> Configure()
        {
            var allowedHosts = new List<StringSegment>();
            if (_options.AllowedHosts?.Count > 0 && !TryProcessHosts(_options.AllowedHosts, allowedHosts))
            {
                _logger.WildcardDetected();
                _allowedHosts = allowedHosts;
                _allowAnyNonEmptyHost = true;
                return _allowedHosts;
            }

            if (allowedHosts.Count == 0)//至少一个Host
            {
                throw new InvalidOperationException("No allowed hosts were configured.");
            }

            if (_logger.IsEnabled(LogLevel.Debug))
            {
                _logger.AllowedHosts(string.Join("; ", allowedHosts));
            }

            _allowedHosts = allowedHosts;
            return _allowedHosts;
        }

总结

这篇文章主要也许能给你们开阔一下思惟,其实他的实现逻辑很简单,当咱们请求带着Host头去访问的时候,经过该中间件判断该Host头是否在咱们预先配置好的里面,若是在里面那么就继续请求下一个中间件,若是说不在那么很差意思400中间件

相关文章
相关标签/搜索