Skip to content

Instantly share code, notes, and snippets.

@mattmazzola
Created April 2, 2014 17:55
Show Gist options
  • Save mattmazzola/9939437 to your computer and use it in GitHub Desktop.
Save mattmazzola/9939437 to your computer and use it in GitHub Desktop.
WebAPI CORS Regex support for origin.
[AttributeUsage(AttributeTargets.Method | AttributeTargets.Class, AllowMultiple = false)]
public class SubdomainWildcard : Attribute, ICorsPolicyProvider
{
private static List<string> AcceptableDomainPatterns = new List<string>()
{
@"mattmazzola([-\w]+)\.sharepoint\.com"
};
public async Task<CorsPolicy> GetCorsPolicyAsync(HttpRequestMessage request, CancellationToken token)
{
var corsRequestContext = request.GetCorsRequestContext();
var originRequested = corsRequestContext.Origin;
if (await IsOriginAcceptable(originRequested))
{
// Grant CORS request
var policy = new CorsPolicy
{
AllowAnyHeader = true,
AllowAnyMethod = true,
};
policy.Origins.Add(originRequested);
return policy;
}
else
{
return null;
}
}
private async Task<Boolean> IsOriginAcceptable(string origin)
{
var isOriginAcceptable = false;
// Iterate through each pattern available
// If the origin is matched by one of the regex patterns
// return true, else return false;
foreach (var pattern in AcceptableDomainPatterns)
{
var regex = new Regex(pattern, RegexOptions.IgnoreCase);
if (regex.IsMatch(origin))
{
isOriginAcceptable = true;
break;
}
}
return isOriginAcceptable;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment