Skip to content

Commit

Permalink
cors fix
Browse files Browse the repository at this point in the history
  • Loading branch information
HaikAsatryan committed Aug 27, 2024
1 parent dd49476 commit a63f96b
Showing 1 changed file with 59 additions and 4 deletions.
63 changes: 59 additions & 4 deletions src/Pandatech.CleanArchitecture.Api/Extensions/CorsExtension.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using Pandatech.CleanArchitecture.Infrastructure.Helpers;
using RegexBox;

namespace Pandatech.CleanArchitecture.Api.Extensions;

Expand All @@ -8,11 +9,14 @@ public static WebApplicationBuilder AddCors(this WebApplicationBuilder builder)
{
if (builder.Environment.IsProduction())
{
var allowedOrigins = builder.Configuration
.GetAllowedCorsOrigins()
.SplitOrigins()
.EnsureWwwAndNonWwwVersions();

builder.Services.AddCors(options => options.AddPolicy("AllowSpecific",
p => p
.WithOrigins(builder.Configuration
.GetAllowedCorsOrigins()
.SplitOrigins())
.WithOrigins(allowedOrigins)
.AllowCredentials()
.AllowAnyMethod()
.AllowAnyHeader()));
Expand Down Expand Up @@ -49,8 +53,59 @@ private static string[] SplitOrigins(this string input)
{
result[i] = result[i]
.Trim();

if (PandaValidator.IsUri(result[i], false))
{
continue;
}

Console.WriteLine($"Removed invalid cors origin: {result[i]}");
result[i] = string.Empty;
}

return result.Where(x => !string.IsNullOrEmpty(x))
.ToArray();
}

private static string[] EnsureWwwAndNonWwwVersions(this string[] uris)
{
var result = new HashSet<string>(StringComparer.OrdinalIgnoreCase);

foreach (var uri in uris)
{
if (!Uri.TryCreate(uri, UriKind.Absolute, out var parsedUri))
{
continue;
}

var uriString = parsedUri.ToString()
.TrimEnd('/');

result.Add(uriString);


var hostWithoutWww = parsedUri.Host.StartsWith("www.")
? parsedUri.Host.Substring(4)
: parsedUri.Host;

var uriWithoutWww = new UriBuilder(parsedUri)
{
Host = hostWithoutWww
}.Uri
.ToString()
.TrimEnd('/');

var uriWithWww = new UriBuilder(parsedUri)
{
Host = "www." + hostWithoutWww
}.Uri
.ToString()
.TrimEnd('/');

result.Add(uriWithoutWww);
result.Add(uriWithWww);
}

return result;
return new List<string>(result).ToArray();
}
}

0 comments on commit a63f96b

Please sign in to comment.