From 0ad2605ca2d421f8ad70fc7b953ac3d6b8191160 Mon Sep 17 00:00:00 2001 From: gambitier Date: Thu, 11 May 2023 05:04:10 +0530 Subject: [PATCH] add CORS policy configs --- src/bundles/Elsa.AllInOne.Web/Program.cs | 28 ++++++++++++++++++- .../Elsa.AllInOne.Web/appsettings.json | 5 ++++ 2 files changed, 32 insertions(+), 1 deletion(-) diff --git a/src/bundles/Elsa.AllInOne.Web/Program.cs b/src/bundles/Elsa.AllInOne.Web/Program.cs index 1f15e4bc86..270a41d3ac 100644 --- a/src/bundles/Elsa.AllInOne.Web/Program.cs +++ b/src/bundles/Elsa.AllInOne.Web/Program.cs @@ -4,6 +4,7 @@ using Elsa.EntityFrameworkCore.Modules.Runtime; using Elsa.Webhooks.Extensions; using Microsoft.AspNetCore.Mvc; +using Microsoft.AspNetCore.Cors.Infrastructure; var builder = WebApplication.CreateBuilder(args); builder.WebHost.UseStaticWebAssets(); @@ -42,7 +43,32 @@ ); services.AddHealthChecks(); -services.AddCors(cors => cors.AddDefaultPolicy(policy => policy.AllowAnyHeader().AllowAnyMethod().AllowAnyOrigin())); + +static bool AllowAny(IList Values) => Values.Count == 0 || Values[0] == "*"; +services.AddCors(cors => { + IConfigurationSection corsPolicyConfiguration = configuration.GetSection("CorsPolicy"); + CorsPolicy corsPolicy = corsPolicyConfiguration.Get() ?? new CorsPolicy(); + cors.AddDefaultPolicy(policy => { + var headers = corsPolicy.Headers; + var origins = corsPolicy.Origins; + var methods = corsPolicy.Methods; + + if (AllowAny(headers)) + policy.AllowAnyHeader(); + else + policy.WithHeaders(headers.ToArray()); + + if (AllowAny(origins)) + policy.AllowAnyOrigin(); + else + policy.WithOrigins(origins.ToArray()); + + if (AllowAny(methods)) + policy.AllowAnyMethod(); + else + policy.WithMethods(methods.ToArray()); + }); +}); // Razor Pages. services.AddRazorPages(options => options.Conventions.ConfigureFilter(new IgnoreAntiforgeryTokenAttribute())); diff --git a/src/bundles/Elsa.AllInOne.Web/appsettings.json b/src/bundles/Elsa.AllInOne.Web/appsettings.json index 2149a7ae65..fde56b47bc 100644 --- a/src/bundles/Elsa.AllInOne.Web/appsettings.json +++ b/src/bundles/Elsa.AllInOne.Web/appsettings.json @@ -69,5 +69,10 @@ "Url": "https://localhost:5002/api/webhooks/run-task" } ] + }, + "CorsPolicy": { + "Origins": [], + "Methods": [], + "Headers": [] } }