WebApi 2.2 Cross-Origin Support - asp.net

I'm trying to add CORS support to my API. I've added the nuget package Microsoft.AspNet.WebApi.Cors. I've added this to my WebgApiConfig.cs file, in Register
config.EnableCors(new EnableCorsAttribute("*", "*", "*"));
I've also tried configuring at the Controller. No matter what I try, the Access-Control-Allow-Origin header doesn't get added to the response and I get this message in Chrome when I execute javascript
No 'Access-Control-Allow-Origin' header is present on the requested resource.
Origin 'http://localhost:19560' is therefore not allowed access. The response had HTTP status code 401
Any thoughts on what I may be missing?
It now works if I set the ajax contentType
contentType: 'text/plain'
Apparently this is needed because no route handles the preflight Options request from the browser. Now I need to figure out how to handle the preflight options check so I don't have to set the contentType.

A very good tutorial with solution for cross-origin support via CORS:
http://www.codeproject.com/Articles/843044/Getting-started-with-AngularJS-and-ASP-NET-MVC-The
It's actually just a nuget package to install:
Install-Package Microsoft.Owin.Cors
In Startup.cs, amend Configuration so it contains the following:
public void Configuration(IAppBuilder app)
{
app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);
ConfigureAuth(app);
}

Related

Get CORS request works but Put CORS request fails in AWS Lambda proxy integration (.net6)

I am building a collection of lambdas with proxy integration, using AWS Serverless (SAM).
I am trying my Lambdas from a frontend I have in Blazor WASM. When a GET request is issued, then I get my results on my browser without CORS issues.
But I cannot issue a PUT request without getting the dreaded:
Access to fetch at 'https://myapi.execute-api.eu-central-1.amazonaws.com/Prod/updatevictual?userId=georanto#gmail.com&victualId=da1b2daa-3a73-425e-812e-e2f164f54507' from origin 'https://localhost:7260' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
If I create a dedicated OPTIONS Lambda for the PUT related end-point (as suggested here) then it works. I cannot have an OPTIONS Lambda because I intend to add authentication and the OPTIONS lambda does not work with it.
According to this it should be enough to send the headers as a response. And in the case of GET it is!
To fill in my response headers(adjusting for .net6), I set my cors by attaching the headers at the returned request thus:
private static APIGatewayProxyResponse AllowCors(this APIGatewayProxyResponse response)
{
response.Headers ??= new Dictionary<string, string>();
response.Headers.Add("Access-Control-Allow-Headers",
"Content-Type, Authorization, X-Amz-Date, X-Api-Key, X-Amz-Security-Token");
response.Headers.Add("Access-Control-Allow-Methods", "*");
response.Headers.Add("Access-Control-Allow-Origin", "*");
response.Headers.Add("Access-Control-Allow-Credentials", "false");
return response;
}
I am also logging my responses in Cloudwatch and the put response after the postman request is thus:
2022-05-12T06:08:30.297Z ecffb8ac-0cd9-4626-be96-6260e7a76d47 info Responding with:[{
"statusCode": 201,
"headers": {
"Access-Control-Allow-Headers": "Content-Type, Authorization, X-Amz-Date, X-Api-Key, X-Amz-Security-Token",
"Access-Control-Allow-Methods": "*",
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Credentials": "false"
},
"multiValueHeaders": null,
"body": null,
"isBase64Encoded": false}]
When I issue the request in Postman I see in the response's headers that the CORS headers are set the way they were supposed to:
So I don't think that this is a code issue.
I have also tried to put all the methods (i.e. response.Headers.Add("Access-Control-Allow-Methods", "OPTIONS, DELETE, GET, HEAD, PATCH, POST, PUT") but also didn't work.
Any other ideas what could that be?
I "think" I had the same issue but I'm not familiar with .net... in your cloudfront distribution configuration, be sure to have a caching behavior that allows for put/patch/etc. and configure in that behavior a cache policy that depends on your headers

ASP.NET WebAPI2 and AngularJS

I'm using firefox to perform a connection between an AngularJS/HTML client page and a controller on the ASP.NET WebAPI.
The issue is that I keep getting the "Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://localhost:44377/project/all. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing)." unless I enable the CORS firefox extension.
Even with that enabled, my page doesn't seem to be grabbing the required data; but the errors are gone.
[EnableCors(origins: "https://localhost:PortNumberHereWithoutTheForwardSlah", headers: "", methods: "")] above my Controller:ApiController and used the config.EnableCors(); in the WebApi.Config in App_Start.
Note: the method that uses [HttpGet] does work when I try to use it in my browser.
</system.webServer> Thanks, but I found inserting this between /handlers and /system.webServer in Web.config to be more flexible from another post.

OPTIONS HTTP method instead of GET

I am new to ember js using version 3. From a route I am using this line
this.get('store').findAll('users');
Instead of setting HTTP method GET, it is setting HTTP method OPTIONS.
Because of server is getting OPTIONS as HTTP method, server side i am getting error.
io.katharsis.errorhandling.exception.MethodNotFoundException: OPTIONS:
/users/
and in browser I am getting this error
Request header field Access-Control-Allow-Origin is not allowed by Access-Control-Allow-Headers in preflight response.
I am having the below code in application adapter and #CrossOrigin(origins="*") on Spring Rest API side.
import DS from 'ember-data';
export default DS.JSONAPIAdapter.extend({
init() {
this._super(...arguments);
this.set('headers', {
'Access-Control-Allow-Origin': '*'
});
},
host: 'http://localhost:8082',
namespace: 'spring-katharsis'
});
If the request contain HTTP method GET, I think it may solve the issue.
Please help on this.

Cors doesnt solve cross origin requests

I have trying to build an angular app using ASP.NET MVC Web API.
When i make a $resource request to my web server (localhost) I get
XMLHttpRequest cannot load http://localhost:59636/api/studios. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:44060' is therefore not allowed access. The response had HTTP status code 401.
I read that installing Cors would solve this. But it doesnt. I have tried both enabling cors
config.EnableCors(new EnableCorsAttribute("*", "*", "*"));
as well as using an the attribute
[EnableCorsAttribute("*", "*", "*")]
It is working on IE
In your WebApiConfig.cs file you should have:
config.EnableCors();
In your ApplicationOAuthProvider.cs, in GrantResourceOwnerCredentials():
context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin",
new[] { "http://localhost:44060" });
And over the controller:
[EnableCorsAttribute("http://localhost:44060", "*", "*")]

How can I expose the custom header 'Access-Control-Allow-Origin' in WebApi.Cors - 5.2.2

I have a ASP.Net WebAPI application using:
Microsoft.AspNet.Cors - 5.2.2
Microsoft.AspNet.WebApi.Cors - 5.2.2
Microsoft.AspNet.WebApi - 5.2.0
Please note I had some problems displaying the http address with stackoverflow so it might look a bit strange on this question:
I have set the following:
var cors = new EnableCorsAttribute("`http://localhost:4181`", "*", "*", "X-Custom-Header");
config.EnableCors(cors);
and in my controller:
[EnableCors(origins: "`http://localhost:4181`", headers: "*", methods: "*", exposedHeaders: "X-Custom-Header", SupportsCredentials = true)]
[OverrideAuthentication]
[HostAuthentication(DefaultAuthenticationTypes.ExternalCookie)]
[AllowAnonymous]
[Route("ExternalLogin", Name = "ExternalLogin")]
public async Task<IHttpActionResult> GetExternalLogin(string provider, string error = null)
When I access the site with IE11 I can login to the site (Ajax login) the correct response is sent back but I don't see any customer headers saying Access-Control-Allow-Origin. IE accepts what came back and takes me to the next page.
When I access the site with Chrome I can login to the site (Ajax login) the correct response is sent back but I don't see any customer headers saying Access-Control-Allow-Origin. Crome does not accept the resonse and even though there's a 200 code returned it does not go to the next page. Instead it gives this message in the console:
XMLHttpRequest cannot load http://localhost:3048/Token. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:4181' is therefore not allowed access. The response had HTTP status code 502.
When I check with fiddler both the IE and the Chome calls return the correct access data from the login but Crome goes no further than displaying the console error message.
Add the following line of code to GrantResourceOwnerCredentials, which will add the header to the response.
context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "*" });
Check my answer here ASP.NET WEB API 2 OWIN Authentication unsuported grant_Type
and my article here, where you can find a working project with CORS enabled.
I have had problems setting
Access-Control-Allow-Origin: *
Some browsers do not accept *, but requires the response to contain the domain name of the originating request, like this:
Access-Control-Allow-Origin: stackoverflow.com
Therefore (and for security reasons): On the server, read the domain the request originates from, compare this against a whitelist, set Access-Control-Allow-Origin to the domain the request originates from.

Resources