Created
April 2, 2014 17:55
-
-
Save mattmazzola/9939437 to your computer and use it in GitHub Desktop.
WebAPI CORS Regex support for origin.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
[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