Skip to content

Commit

Permalink
(#2) add cors lib
Browse files Browse the repository at this point in the history
  • Loading branch information
SaintAngeLs committed Sep 27, 2024
1 parent 4f591d7 commit 7b0bd08
Show file tree
Hide file tree
Showing 13 changed files with 4,790 additions and 18 deletions.
79 changes: 79 additions & 0 deletions src/Nuar.Cors/src/Nuar.Cors/Core/CorsOptionsBuilder.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
using System;
using System.Collections.Generic;
using System.Linq;

namespace Nuar.Cors.Core
{
public class CorsOptionsBuilder : IOptionsBuilder<CorsOptions>
{
private readonly CorsOptions _options;

public CorsOptionsBuilder()
{
_options = new CorsOptions
{
AllowedOrigins = new List<string>(),
AllowedMethods = new List<string>(),
AllowedHeaders = new List<string>(),
ExposedHeaders = new List<string>(),
Environment = new Dictionary<string, CorsEnvironment>()
};
}

public CorsOptionsBuilder AllowCredentials(bool allow)
{
_options.AllowCredentials = allow;
return this;
}

public CorsOptionsBuilder WithAllowedOrigins(params string[] origins)
{
_options.AllowedOrigins = origins;
return this;
}

public CorsOptionsBuilder WithDeniedOrigins(params string[] deniedOrigins)
{
_options.DeniedOrigins = deniedOrigins;
return this;
}

public CorsOptionsBuilder WithAllowedMethods(params string[] methods)
{
_options.AllowedMethods = methods;
return this;
}

public CorsOptionsBuilder WithAllowedHeaders(params string[] headers)
{
_options.AllowedHeaders = headers;
return this;
}

public CorsOptionsBuilder WithExposedHeaders(params string[] headers)
{
_options.ExposedHeaders = headers;
return this;
}

public CorsOptionsBuilder WithMaxAge(int maxAge)
{
_options.MaxAge = maxAge;
return this;
}

public CorsOptionsBuilder EnableLogging(bool enable)
{
_options.LoggingEnabled = enable;
return this;
}

public CorsOptionsBuilder WithEnvironment(string environment, CorsEnvironment corsEnvironment)
{
_options.Environment[environment] = corsEnvironment;
return this;
}

public CorsOptions Build() => _options;
}
}
74 changes: 74 additions & 0 deletions src/Nuar.Cors/src/Nuar.Cors/CorsExtension.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
using System;
using System.Linq;
using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Nuar.Cors;
using Nuar.Cors.Core;

namespace Nuar.Extensions.Cors
{
public class CorsExtension : IExtension
{
public string Name => "cors";
public string Description => "Cross-Origin Resource Sharing";
public string Version => "1.0.0";

public void Add(IServiceCollection services, IOptionsProvider optionsProvider)
{
var options = optionsProvider.GetForExtension<CorsOptions>(Name); // Ensure CorsOptions implements IOptions

services.AddCors(cors =>
{
var allowedHeaders = options.AllowedHeaders ?? Enumerable.Empty<string>();
var allowedMethods = options.AllowedMethods ?? Enumerable.Empty<string>();
var allowedOrigins = options.AllowedOrigins ?? Enumerable.Empty<string>();
var exposedHeaders = options.ExposedHeaders ?? Enumerable.Empty<string>();

cors.AddPolicy("CorsPolicy", builder =>
{
var origins = allowedOrigins.ToArray();
if (options.AllowCredentials && origins.FirstOrDefault() != "*")
{
builder.AllowCredentials();
}
else
{
builder.DisallowCredentials();
}

// Handle Denied Origins
if (options.DeniedOrigins != null && options.DeniedOrigins.Any())
{
origins = origins.Except(options.DeniedOrigins).ToArray();
}

builder.WithHeaders(allowedHeaders.ToArray())
.WithMethods(allowedMethods.ToArray())
.WithOrigins(origins)
.WithExposedHeaders(exposedHeaders.ToArray());

// Apply MaxAge
if (options.MaxAge.HasValue)
{
builder.SetPreflightMaxAge(TimeSpan.FromSeconds(options.MaxAge.Value));
}
});
});
}

public void Use(IApplicationBuilder app, IOptionsProvider optionsProvider)
{
var options = optionsProvider.GetForExtension<CorsOptions>(Name); // Ensure CorsOptions implements IOptions

// Handle Logging
if (options.LoggingEnabled)
{
var logger = app.ApplicationServices.GetRequiredService<ILogger<CorsExtension>>();
logger.LogInformation("CORS policy is applied.");
}

app.UseCors("CorsPolicy");
}
}
}
12 changes: 4 additions & 8 deletions src/Nuar.Cors/src/Nuar.Cors/CorsOptions.cs
Original file line number Diff line number Diff line change
@@ -1,12 +1,8 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Nuar.Cors.Core;

namespace Nuar.Cors
namespace Nuar.Cors.Core
{
public class CorsOptions
public class CorsOptions : IOptions
{
public bool AllowCredentials { get; set; }
public IEnumerable<string> AllowedOrigins { get; set; }
Expand All @@ -15,7 +11,7 @@ public class CorsOptions
public IEnumerable<string> AllowedHeaders { get; set; }
public IEnumerable<string> ExposedHeaders { get; set; }
public int? MaxAge { get; set; }
public bool LoggingEnabled { get; set; }
public bool LoggingEnabled { get; set; }
public Dictionary<string, CorsEnvironment> Environment { get; set; }
}
}
}
7 changes: 7 additions & 0 deletions src/Nuar.Cors/src/Nuar.Cors/IOptionsBuilder.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
namespace Nuar.Cors.Core
{
public interface IOptionsBuilder<TOptions>
{
TOptions Build();
}
}
4 changes: 4 additions & 0 deletions src/Nuar.Cors/src/Nuar.Cors/Nuar.Cors.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -6,4 +6,8 @@
<Nullable>enable</Nullable>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="Nuar" Version="1.0.5" />
</ItemGroup>

</Project>
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@
[assembly: System.Reflection.AssemblyCompanyAttribute("Nuar.Cors")]
[assembly: System.Reflection.AssemblyConfigurationAttribute("Debug")]
[assembly: System.Reflection.AssemblyFileVersionAttribute("1.0.0.0")]
[assembly: System.Reflection.AssemblyInformationalVersionAttribute("1.0.0+ffd419cb94da23dfe0244e2eeb5ed393e94d8d36")]
[assembly: System.Reflection.AssemblyInformationalVersionAttribute("1.0.0+4f591d7d3d29b75a3f95f6e24b0a0ebae4bb1338")]
[assembly: System.Reflection.AssemblyProductAttribute("Nuar.Cors")]
[assembly: System.Reflection.AssemblyTitleAttribute("Nuar.Cors")]
[assembly: System.Reflection.AssemblyVersionAttribute("1.0.0.0")]
Expand Down
Original file line number Diff line number Diff line change
@@ -1 +1 @@
fb691fae5e8ff7ce111567c6ee56426d511e58d292f5e1863854ae2fe85b0dfc
ea5bc4205fb4e0555c31b64def31f340295e00e222ccc672bbca57d617852012
Binary file modified src/Nuar.Cors/src/Nuar.Cors/obj/Debug/net9.0/Nuar.Cors.assets.cache
Binary file not shown.
Binary file not shown.
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,12 @@
"frameworks": {
"net9.0": {
"targetAlias": "net9.0",
"dependencies": {
"Nuar": {
"target": "Package",
"version": "[1.0.5, )"
}
},
"imports": [
"net461",
"net462",
Expand Down
Original file line number Diff line number Diff line change
@@ -1,2 +1,8 @@
<?xml version="1.0" encoding="utf-8" standalone="no"?>
<Project ToolsVersion="14.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003" />
<Project ToolsVersion="14.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ImportGroup Condition=" '$(ExcludeRestorePackageImports)' != 'true' ">
<Import Project="$(NuGetPackageRoot)microsoft.extensions.options/8.0.0/buildTransitive/net6.0/Microsoft.Extensions.Options.targets" Condition="Exists('$(NuGetPackageRoot)microsoft.extensions.options/8.0.0/buildTransitive/net6.0/Microsoft.Extensions.Options.targets')" />
<Import Project="$(NuGetPackageRoot)microsoft.extensions.configuration.binder/8.0.0/buildTransitive/netstandard2.0/Microsoft.Extensions.Configuration.Binder.targets" Condition="Exists('$(NuGetPackageRoot)microsoft.extensions.configuration.binder/8.0.0/buildTransitive/netstandard2.0/Microsoft.Extensions.Configuration.Binder.targets')" />
<Import Project="$(NuGetPackageRoot)microsoft.extensions.logging.abstractions/8.0.0/buildTransitive/net6.0/Microsoft.Extensions.Logging.Abstractions.targets" Condition="Exists('$(NuGetPackageRoot)microsoft.extensions.logging.abstractions/8.0.0/buildTransitive/net6.0/Microsoft.Extensions.Logging.Abstractions.targets')" />
</ImportGroup>
</Project>
Loading

0 comments on commit 7b0bd08

Please sign in to comment.