Skip to content

Instantly share code, notes, and snippets.

@jenyayel
Created May 9, 2017 13:29
Show Gist options
  • Save jenyayel/0676a1106e96568d7e46cde8c9142481 to your computer and use it in GitHub Desktop.
Save jenyayel/0676a1106e96568d7e46cde8c9142481 to your computer and use it in GitHub Desktop.
Writes dynamic `Access-Control-Allow-Origin` header
/// <summary>
/// When using 'withCredentials' in CORS, wildcard '*' cannot be used in the 'Access-Control-Allow-Origin'
/// header. The attribute generates a specific value for this header
/// </summary>
/// <seealso cref="System.Attribute" />
/// <seealso cref="Microsoft.AspNetCore.Cors.Infrastructure.ICorsPolicyProvider" />
[AttributeUsage(AttributeTargets.Method | AttributeTargets.Class, AllowMultiple = false)]
public class SpecificOriginAttribute : Attribute, ICorsPolicyProvider
{
private string _originConfig;
public Task<CorsPolicy> GetPolicyAsync(HttpContext context, string policyName)
{
if (_originConfig == null)
{
var config = context.RequestServices.GetService<IConfigurationRoot>();
_originConfig = config.GetValue<string>("Cors:origins");
}
string origin = _originConfig == "*"
? $"{context.Request.Scheme}://{context.Request.Host}"
: _originConfig;
return Task.FromResult(new CorsPolicyBuilder(origin)
.AllowAnyHeader()
.AllowAnyMethod()
.AllowCredentials()
.Build());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment