public SecurityHeader(
            RequestDelegate next,
            ILoggerFactory loggerFactory,
            CspSettings settings)
        {
            if (loggerFactory == null)
            {
                throw new ArgumentNullException(nameof(loggerFactory));
            }

            _next = next ?? throw new ArgumentNullException(nameof(next));
            _securityHeaderService = new SecurityHeaderService();
            _logger   = loggerFactory.CreateLogger <SecurityHeader>();
            _settings = settings ?? throw new ArgumentNullException(nameof(settings));
        }
Example #2
0
        internal void ApplyResult(HttpResponse response, CspSettings settings)
        {
            var headers = response.Headers;

            StringBuilder stb = new StringBuilder();

            if (!string.IsNullOrWhiteSpace(settings.Default))
            {
                stb.Append($"default-src {settings.Default};");
            }
            if (!string.IsNullOrWhiteSpace(settings.Image))
            {
                stb.Append($"img-src {settings.Image};");
            }
            if (!string.IsNullOrWhiteSpace(settings.Style))
            {
                stb.Append($"style-src {settings.Style};");
            }
            if (!string.IsNullOrWhiteSpace(settings.Font))
            {
                stb.Append($"font-src {settings.Font};");
            }
            if (!string.IsNullOrWhiteSpace(settings.Script))
            {
                stb.Append($"script-src {settings.Script};");
            }
            if (settings.BlockMixedContent)
            {
                // block all mixed contents( force to use https )
                stb.Append("block-all-mixed-content;");
            }
            if (settings.UseHttps)
            {
                // redirect to https
                stb.Append("upgrade-insecure-requests;");
            }

            headers[CSP_HEADER] = stb.ToString();
            foreach (var headerValuePair in SecurityHeader)
            {
                headers[headerValuePair.Key] = headerValuePair.Value;
            }

            foreach (var header in RemoveHeader)
            {
                headers.Remove(header);
            }
        }
Example #3
0
        public static IApplicationBuilder UseSecurityHeader(
            this IApplicationBuilder app,
            Action <CspSettings> configure)
        {
            if (app == null)
            {
                throw new ArgumentNullException(nameof(app));
            }

            if (configure == null)
            {
                throw new ArgumentNullException(nameof(configure));
            }

            var settings = new CspSettings();

            configure(settings);
            return(app.UseMiddleware <SecurityHeader>(settings));
        }