Skip to content

Instantly share code, notes, and snippets.

@kumards
Created March 13, 2018 20:10
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save kumards/7b8dae553ea29ec6e6b34324d50f3056 to your computer and use it in GitHub Desktop.
Save kumards/7b8dae553ea29ec6e6b34324d50f3056 to your computer and use it in GitHub Desktop.
Wildcard Origin Cors Policy
public class WildcardOriginCorsPolicy : Attribute, ICorsPolicyProvider
{
private readonly string _origins;
private readonly string _headers;
private readonly string _methods;
//private readonly CorsPolicy _policy;
//
// Summary:
// Initializes a new instance of the WildcardOriginCorsPolicy class.
//
// Parameters:
// origins:
// Comma-separated list of origins that are allowed to access the resource. Use
// "*" to allow all.
// "*.example.com" for subdomains
//
// headers:
// Comma-separated list of headers that are supported by the resource. Use "*" to
// allow all. Use null or empty string to allow none.
//
// methods:
// Comma-separated list of methods that are supported by the resource. Use "*" to
// allow all. Use null or empty string to allow none.
public WildcardOriginCorsPolicy(string origins, string headers, string methods)
{
this._origins = origins;
this._headers = headers;
this._methods = methods;
}
public bool SupportsCredentials { get; set; }
public Task<CorsPolicy> GetCorsPolicyAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
var policy = CreatePolicy(request.GetCorsRequestContext(), this._origins, this._headers, this._methods);
policy.SupportsCredentials = this.SupportsCredentials;
return Task.FromResult(policy);
}
private static CorsPolicy CreatePolicy(CorsRequestContext requestContext, string origins, string headers, string methods)
{
var corsPolicy = new CorsPolicy();
if (origins == "*")
{
corsPolicy.AllowAnyOrigin = true;
}
else
{
var originsStringArray = origins.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
var requestOrigin = requestContext.Origin.ToLowerInvariant();
foreach (var originItem in originsStringArray)
{
////Check if the current request uri matches with any of the wildcard origins.
if (Regex.IsMatch(requestOrigin, WildCardToRegularExpression(originItem)))
{
corsPolicy.Origins.Add(requestOrigin);
}
}
}
if (!String.IsNullOrEmpty(headers))
{
if (headers == "*")
{
corsPolicy.AllowAnyHeader = true;
}
else
{
var headersStringArray = headers.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
corsPolicy.Headers.AddAll(headersStringArray);
}
}
if (!String.IsNullOrEmpty(methods))
{
if (methods == "*")
{
corsPolicy.AllowAnyMethod = true;
}
else
{
var methodsStringArray = methods.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
corsPolicy.Methods.AddAll(methodsStringArray);
}
}
return corsPolicy;
}
private static string WildCardToRegularExpression(String value)
{
return "^" + Regex.Escape(value).Replace("\\?", ".").Replace("\\*", ".*") + "$";
}
}
@kumards
Copy link
Author

kumards commented Mar 13, 2018

Use it like this.

var cors = new WildcardOriginCorsPolicy("*.example.com,http://localhost:*", "*", "POST,PUT,DELETE,GET,OPTIONS") { SupportsCredentials = true };
config.EnableCors(cors);

@taburetkin
Copy link

taburetkin commented Mar 18, 2018

Is this example for Core or not?

and ICorsPolicyProvider is exists at least in 2 namespaces:
System.Web.Http.Cors and in Microsoft.Owin.Cors

i just trying to realize how to setup custom policy provider in my environment and have some difficulties with it

@kumards
Copy link
Author

kumards commented Jun 28, 2018

It is not for Aspnet Core.

Sorry about the delayed response. I seem to have missed out the notification.

@jpodpro
Copy link

jpodpro commented Jul 31, 2019

where is AddAll coming from? it is not defined anywhere I can find except in what looks like Xamarin libs.

@kumards
Copy link
Author

kumards commented Dec 18, 2019

AddAll came from one of my extensions. You can replace it with custom code.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment