Nathiel Barros Nathiel Barros - 3 years ago 148
C# Question

Cross-Origin Requests WebApi

I was reading https://docs.microsoft.com/en-us/aspnet.... about Security to prevent AJAX requests to another domain and makes me wonder, if I enable this, I would be able to make request from my Android Client? Cu'z it seems that anything outside of that domain, can't be requested. Is that it? Thanks!

Would be something like:

context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "*" });
using (IUserRepository _repository = new UserRepository(new Data.DataContexts.OAuthServerDataContext()))
{
var user = _repository.Authenticate(context.UserName, context.Password);

if (user == null)
{
context.SetError("invalid_grant", "The user name or password is incorrect.");
return;
}
}

Answer Source

If you are making the request from another domain then you will need to set up an Access-Control-Allow-Origin header. You can use * if you aren't concerned about security but it's best to specify only the domains you know will need access.

Non-browser-based clients may not necessarily send the Origin header (e.g. Postman) in which case you likely won't need to worry about setting up CORS.

That documentation you linked is a good start. This post provides a good basic example if you want to set up access globally rather than a per-controller basis.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download