The next generation of the Teknik Services. Written in ASP.NET. https://www.teknik.io/
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

CSPMiddleware.cs 2.5KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Threading.Tasks;
  5. using Microsoft.AspNetCore.Builder;
  6. using Microsoft.AspNetCore.Http;
  7. using Teknik.Configuration;
  8. using Teknik.Utilities;
  9. namespace Teknik.IdentityServer.Middleware
  10. {
  11. // You may need to install the Microsoft.AspNetCore.Http.Abstractions package into your project
  12. public class CSPMiddleware
  13. {
  14. private readonly RequestDelegate _next;
  15. public CSPMiddleware(RequestDelegate next)
  16. {
  17. _next = next;
  18. }
  19. public Task Invoke(HttpContext httpContext, Config config)
  20. {
  21. if (!httpContext.Request.IsLocal())
  22. {
  23. // Default to nothing allowed
  24. string allowedDomain = "'none'";
  25. // Allow this domain
  26. string host = httpContext.Request.Headers["Host"];
  27. if (!string.IsNullOrEmpty(host))
  28. {
  29. string domain = host.GetDomain();
  30. allowedDomain = string.Format("*.{0} {0}", domain);
  31. }
  32. var csp = string.Format(
  33. "default-src 'self'; " +
  34. "script-src blob: 'unsafe-eval' 'unsafe-inline' {0}; " +
  35. "style-src 'unsafe-inline' {0}; " +
  36. "img-src data: *; " +
  37. "font-src data: {0}; " +
  38. "connect-src wss: blob: data: {0}; " +
  39. "media-src *; " +
  40. "worker-src blob: mediastream: {0}; " +
  41. "form-action *; " +
  42. "base-uri {0}; " +
  43. "frame-ancestors {0};",
  44. allowedDomain);
  45. if (!httpContext.Response.Headers.ContainsKey("Content-Security-Policy"))
  46. {
  47. httpContext.Response.Headers.Add("Content-Security-Policy", csp);
  48. }
  49. // and once again for IE
  50. if (!httpContext.Response.Headers.ContainsKey("X-Content-Security-Policy"))
  51. {
  52. httpContext.Response.Headers.Add("X-Content-Security-Policy", csp);
  53. }
  54. }
  55. return _next(httpContext);
  56. }
  57. }
  58. // Extension method used to add the middleware to the HTTP request pipeline.
  59. public static class CSPMiddlewareExtensions
  60. {
  61. public static IApplicationBuilder UseCSP(this IApplicationBuilder builder)
  62. {
  63. return builder.UseMiddleware<CSPMiddleware>();
  64. }
  65. }
  66. }