Reputation: 117
I tried everything but can't enable CORS for my WebApi project. I guess I 'm missing something or not doing it right. My StartUp.config is:
public void Configuration(IAppBuilder app)
{
HttpConfiguration config = new HttpConfiguration();
// Web API routes
//app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);
config.MapHttpAttributeRoutes();
config.EnableCors(new System.Web.Http.Cors.EnableCorsAttribute("http://www.test.ca", "*", "GET,POST")); //enable only for this domain
ConfigureOAuth(app);
app.UseWebApi(config);
ConfigureAutofac(app, config);
}
My api controller:
[HttpPost]
[Authorize]
[Route("api/Accounts/GetTestTest")]
[System.Web.Http.Cors.EnableCors("http://www.test.ca", "*", "*")]
public HttpResponseMessage GetTestTest()
{
return this.Request.CreateResponse(System.Net.HttpStatusCode.OK);
}
Here I should be restricted because my request are made from MVC application which runs on localhost. Also I'm using tokens to authorize users. Any ideas what I am missing or doing wrong?
EDIT Request is comming from MVC controller action like this:
static string CallApi(string url, string token, LogInRequest request)
{
System.Net.ServicePointManager.ServerCertificateValidationCallback += (sender, cert, chain, sslPolicyErrors) => true;
using (var client = new HttpClient())
{
if (!string.IsNullOrWhiteSpace(token))
{
var t = Newtonsoft.Json.JsonConvert.DeserializeObject<CashManager.Models.Global.Token>(token);
client.DefaultRequestHeaders.Clear();
client.DefaultRequestHeaders.Add("Authorization", "Bearer " + t.access_token);
}
var response = client.PostAsJsonAsync<string>(url,string.Empty).Result;
return response.Content.ReadAsStringAsync().Result;
}
}
Upvotes: 0
Views: 207
Reputation: 58723
CORS does not apply to requests made from a back-end. It only applies to requests coming from browsers via AJAX.
You will need to do IP address-based filtering or something else to block requests from certain places. The authentication you have might be good enough though.
Upvotes: 1