Skip to content

Instantly share code, notes, and snippets.

@jglozano
Created February 12, 2018 16:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jglozano/5cc515a005ac3777f830af0ff21520eb to your computer and use it in GitHub Desktop.
Save jglozano/5cc515a005ac3777f830af0ff21520eb to your computer and use it in GitHub Desktop.
Configuration CORS Policy Provider
public class ConfigCorsPolicyProvider : ICorsPolicyProvider
{
private readonly IConfigurationService configurationService;
public ConfigCorsPolicyProvider(IConfigurationService configurationService)
{
this.configurationService = configurationService;
}
public Task<CorsPolicy> GetCorsPolicyAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
var allowedOrigins = configurationService.GetAppSetting("security.AllowedOrigins");
if (string.IsNullOrWhiteSpace(allowedOrigins))
{
var allowAllPolicy = new CorsPolicy
{
AllowAnyHeader = true,
AllowAnyMethod = true,
AllowAnyOrigin = false,
SupportsCredentials = true
};
return Task.FromResult(allowAllPolicy);
}
var origins = allowedOrigins
.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries)
.Select(origin => origin.Trim())
.ToArray();
var policy = new CorsPolicy
{
AllowAnyHeader = true,
AllowAnyMethod = true,
AllowAnyOrigin = false,
SupportsCredentials = true
};
foreach (var origin in origins)
{
policy.Origins.Add(origin);
}
return Task.FromResult(policy);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment