CORS issue on chrome & firefox - asp.net-web-api

The web API from IIS 7.5 are not responding for Chrome & Firefox.
I am getting the following error in chrome
No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://10.xx.xx.xx:81' is therefore not allowed access
Firefox throw 401 unauthorized error.
Works perfectly on IE 11
Are there any additional setting required for these browsers?

First install WebApi Cors NuGet Package:
Install-Package Microsoft.AspNet.WebApi.Cors
Then in your WebApiConfig.cs file:
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
var cors = new EnableCorsAttribute("*", "*", "*");
config.EnableCors(cors);
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
//other code
}
}
This way you enable CORS header globally allowing cross-site requests from any domain. If you want to allow cross-site requests from only a single (or a list of) domain, then change the constructor parameters of EnableCorsAttribute:
new EnableCorsAttribute("http://alloweddomain.com", "*", "*");
You may also apply the EnableCorsAttribute on a Controller or Action basis.
More information on the official documentation: http://www.asp.net/web-api/overview/security/enabling-cross-origin-requests-in-web-api

"A resource makes a cross-origin HTTP request when it requests a resource from a different domain than the one which the first resource itself serves"
You can use a chrome addon to allow CORS:
https://chrome.google.com/webstore/detail/allow-control-allow-origi/nlfbmbojpeacfghkpbjhddihlkkiljbi

Related

Web API 2.0 Routing not working properly when deployed to godaddy

I am getting very strange routing behaviour issue in Asp.net Web API 2.0. When I am running my API in localhost it works fine with URL api/{controller} but now I have deployed this web API to GoDaddy shared server at that time it is working with api/api/{controller}. It is working when I use "api" keyword two times. If I use api/{controller} it gives me
404 error.(resource not found).
Can someone please help me to identify this strange behaviour?
In webapi.config.cs file default route is register.
var cors = new EnableCorsAttribute("*", "*", "*");
config.EnableCors(cors);
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
and On Every controller I have used RoutePrefix as below
[RoutePrefix("api/test")]
public class Testontroller : ApiController
{
}
Thanks In Advance!

Ionic 2 ASP APi token request

I'm Trying to retrieve a bearer token from my ASP API from my ionic2 app.
I have enabled CORS on the API as shown below:
var cors = new EnableCorsAttribute("*", "*", "*");
config.EnableCors(cors);
This enabled me to form a POST request from my ionic 2 app to my API in order to register a user. This works wonderfully.
The request I used for this is as shown below:
let headers = new Headers({
'Content-Type': 'application/json'
});
let options = new RequestOptions({
headers: headers
});
let body = JSON.stringify({
Email: credentials.email,
Password: credentials.password,
ConfirmPassword: credentials.confirmPassword
});
return this.http.post('http://localhost:34417/api/Account/Register', body, options)
However when I try to retrieve a token from my API I receive the following error:
No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8100' is therefore not allowed access.
The request I'm using to try and retrieve the token is as follows:
let body = "grant_type=password" + "&userName=" + credentials.email + "&password=" + credentials.password;
let headers = new Headers({ 'Content-Type': 'application/x-www-form-urlencoded' });
let options = new RequestOptions({ headers: headers });
return this.http.post('http://localhost:34417/token', body, options)
This is the only request that is throwing this error, all other requests to my API work fine.
Have I missed anything, or am I doing something wrong?
var cors = new EnableCorsAttribute("*", "*", "*");
Looks like you are setting Access-Control-Allow-Origin as *.
Check MDN CORS Requests with credentials.
Credentialed requests and wildcards
When responding to a credentialed request, the server must specify an
origin in the value of the Access-Control-Allow-Origin header, instead
of specifying the "*" wildcard.
You will have to set a specific url if you use credentials.
Or if you only intend to use only for ionic 2, you could avoid the cors issue by setting a proxy.
According to the official blog:
The proxies settings contain two things: the path you use to access them on your local Ionic server, and the proxyUrl you’d ultimately like to reach from the API call.
{
"name": "ionic-2-app",
"app_id": "my_id",
"proxies": [
{
"path": "/api",
"proxyUrl": "http://localhost:34417/api"
}
]
}
Ionic serve command by default will start server on localhost:8100.
The set proxy will hit your http://localhost:34417/api.
Your path in the requests will be to the localhost:8100/api instead of your actual server.

Cors not working in web api 2.0

I'm trying very hard to understand and enable CORS in a web api project. I've hit a blocking point. I've started with an ASP.NET MVC Web Api 2 project with an ASP.NET identity. Whatever I do seems to not work.
I've deleted my global.asx file and my startup looks like this:
public partial class Startup
{
public void Configuration(IAppBuilder app)
{
HttpConfiguration configuration = new HttpConfiguration();
// I'm not sure it this is the proper way to use webapiconfig
WebApiConfig.Register(configuration);
app.UseWebApi(configuration);
app.UseCors(CorsOptions.AllowAll);
ConfigureAuth(app);
}
}
and the WebApiConfig.Register code is:
public static void Register(HttpConfiguration config)
{
// Web API configuration and services
// Configure Web API to use only bearer token authentication.
config.SuppressDefaultHostAuthentication();
config.Filters.Add(new HostAuthenticationFilter(OAuthDefaults.AuthenticationType));
config.AddODataQueryFilter();
// Web API routes
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
var jsonFormatter = config.Formatters.OfType<JsonMediaTypeFormatter>().First();
jsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
RegisterModels(); //Automapper here
}
I have the mc aspnet cors and microsoft owin host System web installed.
The "[assembly: OwinStartup(typeof(MyProject.Startup))]" is in place, and in the web.config I have:
<appSettings>
<add key="owin:AutomaticAppStartup" value="true" />
</appSettings>
I only call app.UseCors(CorsOptions.AllowAll) to enable CORS, no other way like config.enableCors or anything else, but whenever I try getting the token or anything in the API, I get the error:
Reason: CORS header ‘Access-Control-Allow-Origin’ missing.
I have tried putting a breakpoint in the Configuration method but it is not called... ever. I'm debugging with IIS Express.
Nothing worked for me.. after many tries I finally managed to get something working.
if you have the same problem..
1) remove anything related to cors from the nugget packages installed .. everything.
2) remove anything related to cors from the web.config.
3) In Gloabal.asax
protected void Application_BeginRequest(object sender, EventArgs e)
{
var context = HttpContext.Current;
var response = context.Response;
response.AddHeader("Access-Control-Allow-Origin", "*");
response.AddHeader("X-Frame-Options", "ALLOW-FROM *");
if (context.Request.HttpMethod == "OPTIONS")
{
response.AddHeader("Access-Control-Allow-Methods", "GET, POST, DELETE, PATCH, PUT");
response.AddHeader("Access-Control-Allow-Headers", "Content-Type, Accept");
response.AddHeader("Access-Control-Max-Age", "1000000");
response.End();
}
}
This work for both /api and /token.
This is a generic solution please be aware before deploying it to prod.
Hope will help anyone who has the same problem.

web api routes not working with CORS enabled.

I have CORS enabled in my web api application. and i have API controllers with both classic REST Function names like Get() and Get(string id) and a controllers with custom function names e.g.
[HttpGet]
GetSomeThing()
i have routes configured like this
config.EnableCors();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{action}/{id}",
defaults: new { id = RouteParameter.Optional }
);
config.Routes.MapHttpRoute(
name: "ApiById",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
with this arrangement i get an error No 'Access-Control-Allow-Origin' header is present when i try to call controller with Classic REST functions.
e.g. /api/Controller
and if i take route with action after route without action , it gives me the same error on controller calls with custom function names.
e.g. /api/Controller/Function
please note that i have
[EnableCorsAttribute("http://localhost:xxxx", "*", "*")]
attribute on both controllers. and these calls are being made from angular application.
kindly advice.
Had the same issue. Fixed it by adding CORS headers directly to web.config. No other changes are needed.
<system.webServer>
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="*" />
<add name="Access-Control-Allow-Methods" value="GET, POST, OPTIONS" />
<add name="Access-Control-Allow-Headers" value="content-type, accept, SOAPAction, origin" />
</customHeaders>
</httpProtocol>
</system.webServer>
Additionally, if you installed CORS via NuGet and were using a previous version of WebAPI, then you may need to uninstall it. CORS will update certain core WebAPI assemblies that may cause compatibility issues, i.e., routes not working.
And of course, you will probably want to limit the allowed origins by replacing the "*" in the Access-Control-Allow-Origin value with the URL's you want to allow.
I ran into this issue and I found it a nightmare to get cors to work.
The fix for me in the end was to remove all references to cors in my app and add just one line in the WebAPIConfig
public static void Register(HttpConfiguration config)
{
config.EnableCors(new EnableCorsAttribute("*", "*", "GET, POST, OPTIONS, PUT, DELETE, TOKEN"));
// Web API routes
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "ActionApi",
routeTemplate: "api/{controller}/{action}/{id}",
defaults: new { id = RouteParameter.Optional }
);
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "rest/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
var jsonFormatter = config.Formatters.OfType<JsonMediaTypeFormatter>().First();
jsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
var json = config.Formatters.JsonFormatter;
json.SerializerSettings.PreserveReferencesHandling = Newtonsoft.Json.PreserveReferencesHandling.Objects;
config.Formatters.Remove(config.Formatters.XmlFormatter);
}
I also removed the custom headers from my web.config. Hope this help anyone else facing cors issues.

WebAPI EnableCors with SupportsCredentials = true not working

I have an MVC site deployed to mysite.mydomain.co that authenticates against ADFS and creates an auth cookie:
public partial class Startup
{
public void ConfigureUserAuth(IAppBuilder app)
{
app.SetDefaultSignInAsAuthenticationType(WsFederationAuthenticationDefaults.AuthenticationType);
app.UseCookieAuthentication(new CookieAuthenticationOptions()
{
AuthenticationType = WsFederationAuthenticationDefaults.AuthenticationType
});
app.UseWsFederationAuthentication(
new WsFederationAuthenticationOptions
{
MetadataAddress = ConfigurationManager.AppSettings["adsfs.MetadataAddress"],
Wtrealm = ConfigurationManager.AppSettings["adsfs.Wtrealm"]
});
}
}
There is also a WebAPI site deployed on "myapi.mydomain.com" with CORS enabled:
GlobalConfiguration.Configuration.EnableCors(new EnableCorsAttribute("https://mysite.mydomain.com", "*", "*") { SupportsCredentials = true });
The the user goes to mysite.mydomain.com. The MVC site authenticates against ADFS and I see the auth cookie being set with no problem.
My application is mostly an SPA, so from javascript there's a AJAX calls to myapi.mydomain.com using jQuery, setting the withCredentials option to true:
$.ajaxSetup({
xhrFields: { withCredentials: true }
});
That options is supposed to send security credentials (cookies) to the API. At runtime I don't see the cookies being set to the API and I get a 401 (unauthorized) error as expected.
If I run the same code on localhost (except for changing the origins to localhost of course) I see the cookie flowing to the API with no problem. My best guess is it works because it's the same subdomain (localhost) whereas on my servers is "mysite" vs "myapi".
Any ideas?

Resources