I have an ASP.NET web API that is being called by three different SPA. I am using windows authentication for the web API. I initially tried to configure CORS in the Web.config l
Create custom attribute using ICorsPolicyProvider
something like following to check if the requested origin is allowed or not
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method,AllowMultiple = false)]
public class EnableCorsForAPIKeysAttribute :
Attribute, ICorsPolicyProvider, IFilter
{
public async Task GetCorsPolicyAsync(
HttpRequestMessage request, CancellationToken cancellationToken)
{
var corsRequestContext = request.GetCorsRequestContext();
var originRequested = corsRequestContext.Origin;
if (await IsValidOrigin(originRequested)) //Check if requested origin is valid or not
{
// Grant CORS request
var policy = new CorsPolicy
{
AllowAnyHeader = true,
AllowAnyMethod = true
};
policy.Origins.Add(originRequested);
return policy;
}
else
{
// Reject CORS request
return null;
}
}
public bool AllowMultiple { get {return false;} }
}
To use it, add it to your API controller
[EnableCorsForAPIKeys]
public class APIBaseController : ApiController
{
}