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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  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. allowedDomain = host;
  30. }
  31. var csp = string.Format(
  32. "default-src 'none'; " +
  33. "script-src blob: 'unsafe-eval' 'nonce-{1}' {0}; " +
  34. "style-src 'unsafe-inline' {0}; " +
  35. "img-src data: *; " +
  36. "font-src data: {0}; " +
  37. "connect-src wss: blob: data: {0}; " +
  38. "media-src *; " +
  39. "worker-src blob: mediastream: {0}; " +
  40. "form-action {0}; " +
  41. "base-uri {0}; " +
  42. "frame-ancestors {0};",
  43. allowedDomain,
  44. httpContext.Items[Constants.NONCE_KEY]);
  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. }