Created
May 9, 2017 13:29
-
-
Save jenyayel/0676a1106e96568d7e46cde8c9142481 to your computer and use it in GitHub Desktop.
Writes dynamic `Access-Control-Allow-Origin` header
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
/// <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