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.

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  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 CORSMiddleware
  13. {
  14. private readonly RequestDelegate _next;
  15. public CORSMiddleware(RequestDelegate next)
  16. {
  17. _next = next;
  18. }
  19. public Task InvokeAsync(HttpContext httpContext, Config config)
  20. {
  21. // Allow this domain, or everything if local
  22. string origin = (httpContext.Request.IsLocal()) ? "*" : httpContext.Request.Headers["Origin"].ToString();
  23. // Is the referrer set to the CDN and we are using a CDN?
  24. if (config.UseCdn && !string.IsNullOrEmpty(config.CdnHost))
  25. {
  26. try
  27. {
  28. string host = httpContext.Request.Headers["Host"];
  29. Uri uri = new Uri(config.CdnHost);
  30. if (host == uri.Host)
  31. origin = host;
  32. }
  33. catch { }
  34. }
  35. string domain = (string.IsNullOrEmpty(origin)) ? string.Empty : origin.GetDomain();
  36. if (string.IsNullOrEmpty(origin))
  37. {
  38. string host = httpContext.Request.Headers["Host"];
  39. string sub = host.GetSubdomain();
  40. origin = (string.IsNullOrEmpty(sub)) ? config.Host : sub + "." + config.Host;
  41. }
  42. else
  43. {
  44. if (domain != config.Host)
  45. {
  46. string sub = origin.GetSubdomain();
  47. origin = (string.IsNullOrEmpty(sub)) ? config.Host : sub + "." + config.Host;
  48. }
  49. }
  50. httpContext.Response.Headers.Append("Access-Control-Allow-Origin", origin);
  51. httpContext.Response.Headers.Append("Vary", "Origin");
  52. return _next(httpContext);
  53. }
  54. }
  55. // Extension method used to add the middleware to the HTTP request pipeline.
  56. public static class CORSMiddlewareExtensions
  57. {
  58. public static IApplicationBuilder UseCORS(this IApplicationBuilder builder)
  59. {
  60. return builder.UseMiddleware<CORSMiddleware>();
  61. }
  62. }
  63. }