Error with 'Access-Control-Allow-Origin' - http

I have a webpage I made with angular 2 that is a form and at the end of it the form must be sent to my java server. But I'm unable to send, I get the error Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:4200' is therefore not allowed access.
I have already changed my server so it will send the Access-Control-Allow headers. The function is like this:
public static Response buildResponse(int status, Object reponseObject, MediaType mediaType) {
Response.ResponseBuilder rb = Response.status(status).entity(reponseObject);
if (mediaType != null) {
rb = rb.type(mediaType);
}
rb = rb.header("Access-Control-Allow-Origin", "*");
rb = rb.header("Access-Control-Allow-Methods", "GET, POST, PATCH, PUT, DELETE, OPTIONS");
rb = rb.header("Access-Control-Allow-Headers", "Origin, Content-Type, X-Auth-Token, accept");
rb = rb.header("Access-Control-Allow-Credentials", true);
System.out.println("teste");
return rb.build();
}
I have also tried to add the header 'Access-Control-Request-Method': 'POST' to the page request, but I still get the error. The problem is not with the software functionality itself because it works fine if I install and activate the CORS plugin for chrome, but I can't request the user to install the plugin to use my site. Does anyone knows what I'm missing? I have been sarching for sometime and the only solutions I found was to disable this browser security (I can't ask the user to do that) and to add the headers on the request, what I already have.

I was finally able to solve my problem. The problem was in the communication between my page and my server. The CORS block is imposed by the browser and the server needs to send a header authorizing the access (the headers I put in the function in the question). What I was missing was the header in the OPTION method. My JavaScript code automatically send and OPTIONS request (the preflight request) before the actual GET or POST method. What I did was to manually implement the OPTIONS method in the server that respond with the necessary headers.

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

while hitting an API Request throws 302 status code how to solve this

I'm hitting an API using http dart library while doing this I'm getting 302 status code. I know that 302 status code is for redirects, can you please say how can i enable redirects in http post method. I have used the following code:
Future<LoginModel> login(String username, String password) async {
var client = new http.Client();
final response =
await client.post(LOGIN_URL +"username=Student&password=2018" ,
headers: {'Content-type': 'application/json',
'Accept': 'application/json'});
if (response.statusCode == 200) {
return LoginModel.fromJson(json.decode(response.body));
} else {
throw Exception('Failed to load post');
}
}
302 is a status code returned by the server to indicate that the client should retry the request using a different URL. It's a way to redirect the client to a different endpoint.
The problem is that only GET (or HEAD) requests can be retried automatically. You are using a POST.
If the 302 status code is received in response to a request other than
GET or HEAD, the user agent MUST NOT automatically redirect the
request unless it can be confirmed by the user, since this might
change the conditions under which the request was issued.
A well-behaved API should probably not issue 30X in response to a POST, but it is. The way to get around this is to make a new http request with the redirected URL. (You might want to put it in a while loop to keep following the redirects until you get to 200, or some error, or reach a timeout/limit.)
add header with
"Accept":"application/json" . henceforth it will only return json data otherwise it will prompt to redirect with html url, default dio configuration does not have response type so you have to mention it in header.
This is because of some issue with the URL that you use. status code 302, says that the URL you are using has been moved or redirected.
May be the loginurl that you are using has certificates now and using https:// instead of http://

Fetch API, custom request headers, CORS, and cross-origin redirects

I need to make an HTTP GET request with custom request headers in-browser and process the result as it streams in. The Fetch API is ideal for this:
fetch('https://example.com/resource', {
method: 'GET',
headers: {
'X-Brad-Test': 'true'
},
cache: 'no-store',
mode: 'cors'
}).then((res) => {
const reader = res.body.getReader();
// etc.
});
This works quite well. Since there are custom headers, the browser pre-flights the request with an OPTIONS request to /resource. I have configured my server to respond with a 204 No Content and the following headers:
Access-Control-Allow-Headers: X-Requested-With, Range, If-Range, X-Brad-Test
Access-Control-Allow-Origin: *
The browser is happy with this, then makes a GET request, the server returns a 200 OK with the data, and the browser allows me to access the response headers and body.
The problem comes in when there is a redirect. The OPTIONS request succeeds with the 204 No Content and the same headers as before. The browser makes the correct GET request, and on the server I send a 302 with a Location: header. Chrome throws the following error:
Fetch API cannot load https://example.com/resource. Redirect from 'https://example.com/resource' to 'http://some-other-origin/resource' has been blocked by CORS policy: Request requires preflight, which is disallowed to follow cross-origin redirect.
This was unexpected, and seems nonsensical to me. I expected the browser to follow the redirect, and do another pre-flight request for this new location, but it didn't do that.
Stranger still is that I can sort of hack around this client-side. I can make an HTTP request without my custom header, figure out where I ended up after redirects by looking at the Response object, then make a second request at the new target with my custom headers. This doesn't work in all cases of course, and I'd rather not rely on this hack. I'd rather find a proper way.
Two Questions:
What is the proper way to allow the client to follow redirects? Is there some sort of Access-Control-* header I can use?
Why does this restriction exist? What security issue is prevented by not following and running pre-flight on the followed URL?
Supporting redirects to requests that require a preflight is very recent change to Fetch (which defines CORS).
https://github.com/whatwg/fetch/commit/0d9a4db8bc02251cc9e391543bb3c1322fb882f2
I believe some implementations have started adjusting their implementations, but this will take some time to reach everyone.

Why is an OPTIONS request sent and can I disable it?

I am building a web API. I found whenever I use Chrome to POST, GET to my API, there is always an OPTIONS request sent before the real request, which is quite annoying. Currently, I get the server to ignore any OPTIONS requests. Now my question is what's good to send an OPTIONS request to double the server's load? Is there any way to completely stop the browser from sending OPTIONS requests?
edit 2018-09-13: added some precisions about this pre-flight request and how to avoid it at the end of this reponse.
OPTIONS requests are what we call pre-flight requests in Cross-origin resource sharing (CORS).
They are necessary when you're making requests across different origins in specific situations.
This pre-flight request is made by some browsers as a safety measure to ensure that the request being done is trusted by the server.
Meaning the server understands that the method, origin and headers being sent on the request are safe to act upon.
Your server should not ignore but handle these requests whenever you're attempting to do cross origin requests.
A good resource can be found here http://enable-cors.org/
A way to handle these to get comfortable is to ensure that for any path with OPTIONS method the server sends a response with this header
Access-Control-Allow-Origin: *
This will tell the browser that the server is willing to answer requests from any origin.
For more information on how to add CORS support to your server see the following flowchart
http://www.html5rocks.com/static/images/cors_server_flowchart.png
edit 2018-09-13
CORS OPTIONS request is triggered only in somes cases, as explained in MDN docs:
Some requests don’t trigger a CORS preflight. Those are called “simple requests” in this article, though the Fetch spec (which defines CORS) doesn’t use that term. A request that doesn’t trigger a CORS preflight—a so-called “simple request”—is one that meets all the following conditions:
The only allowed methods are:
GET
HEAD
POST
Apart from the headers set automatically by the user agent (for example, Connection, User-Agent, or any of the other headers with names defined in the Fetch spec as a “forbidden header name”), the only headers which are allowed to be manually set are those which the Fetch spec defines as being a “CORS-safelisted request-header”, which are:
Accept
Accept-Language
Content-Language
Content-Type (but note the additional requirements below)
DPR
Downlink
Save-Data
Viewport-Width
Width
The only allowed values for the Content-Type header are:
application/x-www-form-urlencoded
multipart/form-data
text/plain
No event listeners are registered on any XMLHttpRequestUpload object used in the request; these are accessed using the XMLHttpRequest.upload property.
No ReadableStream object is used in the request.
Have gone through this issue, below is my conclusion to this issue and my solution.
According to the CORS strategy (highly recommend you read about it) You can't just force the browser to stop sending OPTIONS request if it thinks it needs to.
There are two ways you can work around it:
Make sure your request is a "simple request"
Set Access-Control-Max-Age for the OPTIONS request
Simple request
A simple cross-site request is one that meets all the following conditions:
The only allowed methods are:
GET
HEAD
POST
Apart from the headers set automatically by the user agent (e.g. Connection, User-Agent, etc.), the only headers which are allowed to be manually set are:
Accept
Accept-Language
Content-Language
Content-Type
The only allowed values for the Content-Type header are:
application/x-www-form-urlencoded
multipart/form-data
text/plain
A simple request will not cause a pre-flight OPTIONS request.
Set a cache for the OPTIONS check
You can set a Access-Control-Max-Age for the OPTIONS request, so that it will not check the permission again until it is expired.
Access-Control-Max-Age gives the value in seconds for how long the response to the preflight request can be cached for without sending another preflight request.
Limitation Noted
For Chrome, the maximum seconds for Access-Control-Max-Age is 600 which is 10 minutes, according to chrome source code
Access-Control-Max-Age only works for one resource every time, for example, GET requests with same URL path but different queries will be treated as different resources. So the request to the second resource will still trigger a preflight request.
Please refer this answer on the actual need for pre-flighted OPTIONS request: CORS - What is the motivation behind introducing preflight requests?
To disable the OPTIONS request, below conditions must be satisfied for ajax request:
Request does not set custom HTTP headers like 'application/xml' or 'application/json' etc
The request method has to be one of GET, HEAD or POST. If POST, content type should be one of application/x-www-form-urlencoded, multipart/form-data, or text/plain
Reference:
https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS
When you have the debug console open and the Disable Cache option turned on, preflight requests will always be sent (i.e. before each and every request). if you don't disable the cache, a pre-flight request will be sent only once (per server)
Yes it's possible to avoid options request. Options request is a preflight request when you send (post) any data to another domain. It's a browser security issue. But we can use another technology: iframe transport layer. I strongly recommend you forget about any CORS configuration and use readymade solution and it will work anywhere.
Take a look here:
https://github.com/jpillora/xdomain
And working example:
http://jpillora.com/xdomain/
For a developer who understands the reason it exists but needs to access an API that doesn't handle OPTIONS calls without auth, I need a temporary answer so I can develop locally until the API owner adds proper SPA CORS support or I get a proxy API up and running.
I found you can disable CORS in Safari and Chrome on a Mac.
Disable same origin policy in Chrome
Chrome: Quit Chrome, open an terminal and paste this command: open /Applications/Google\ Chrome.app --args --disable-web-security --user-data-dir
Safari: Disabling same-origin policy in Safari
If you want to disable the same-origin policy on Safari (I have 9.1.1), then you only need to enable the developer menu, and select "Disable Cross-Origin Restrictions" from the develop menu.
As mentioned in previous posts already, OPTIONS requests are there for a reason. If you have an issue with large response times from your server (e.g. overseas connection) you can also have your browser cache the preflight requests.
Have your server reply with the Access-Control-Max-Age header and for requests that go to the same endpoint the preflight request will have been cached and not occur anymore.
I have solved this problem like.
if($_SERVER['REQUEST_METHOD'] == 'OPTIONS' && ENV == 'devel') {
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Headers: X-Requested-With');
header("HTTP/1.1 200 OK");
die();
}
It is only for development. With this I am waiting 9ms and 500ms and not 8s and 500ms. I can do that because production JS app will be on the same machine as production so there will be no OPTIONS but development is my local.
You can't but you could avoid CORS using JSONP.
you can also use a API Manager (like Open Sources Gravitee.io) to prevent CORS issues between frontend app and backend services by manipulating headers in preflight.
Header used in response to a preflight request to indicate which HTTP headers can be used when making the actual request :
content-type
access-control-allow-header
authorization
x-requested-with
and specify the "allow-origin" = localhost:4200 for example
After spending a whole day and a half trying to work through a similar problem I found it had to do with IIS.
My Web API project was set up as follows:
// WebApiConfig.cs
public static void Register(HttpConfiguration config)
{
var cors = new EnableCorsAttribute("*", "*", "*");
config.EnableCors(cors);
//...
}
I did not have CORS specific config options in the web.config > system.webServer node like I have seen in so many posts
No CORS specific code in the global.asax or in the controller as a decorator
The problem was the app pool settings.
The managed pipeline mode was set to classic (changed it to integrated) and the Identity was set to Network Service (changed it to ApplicationPoolIdentity)
Changing those settings (and refreshing the app pool) fixed it for me.
OPTIONS request is a feature of web browsers, so it's not easy to disable it. But I found a way to redirect it away with proxy. It's useful in case that the service endpoint just cannot handle CORS/OPTIONS yet, maybe still under development, or mal-configured.
Steps:
Setup a reverse proxy for such requests with tools of choice (nginx, YARP, ...)
Create an endpoint just to handle the OPTIONS request. It might be easier to create a normal empty endpoint, and make sure it handles CORS well.
Configure two sets of rules for the proxy. One is to route all OPTIONS requests to the dummy endpoint above. Another to route all other requests to actual endpoint in question.
Update the web site to use proxy instead.
Basically this approach is to cheat browser that OPTIONS request works. Considering CORS is not to enhance security, but to relax the same-origin policy, I hope this trick could work for a while. :)
One solution I have used in the past - lets say your site is on mydomain.com, and you need to make an ajax request to foreigndomain.com
Configure an IIS rewrite from your domain to the foreign domain - e.g.
<rewrite>
<rules>
<rule name="ForeignRewrite" stopProcessing="true">
<match url="^api/v1/(.*)$" />
<action type="Rewrite" url="https://foreigndomain.com/{R:1}" />
</rule>
</rules>
</rewrite>
on your mydomain.com site - you can then make a same origin request, and there's no need for any options request :)
It can be solved in case of use of a proxy that intercept the request and write the appropriate headers.
In the particular case of Varnish these would be the rules:
if (req.http.host == "CUSTOM_URL" ) {
set resp.http.Access-Control-Allow-Origin = "*";
if (req.method == "OPTIONS") {
set resp.http.Access-Control-Max-Age = "1728000";
set resp.http.Access-Control-Allow-Methods = "GET, POST, PUT, DELETE, PATCH, OPTIONS";
set resp.http.Access-Control-Allow-Headers = "Authorization,Content-Type,Accept,Origin,User-Agent,DNT,Cache-Control,X-Mx-ReqToken,Keep-Alive,X-Requested-With,If-Modified-Since";
set resp.http.Content-Length = "0";
set resp.http.Content-Type = "text/plain charset=UTF-8";
set resp.status = 204;
}
}
What worked for me was to import "github.com/gorilla/handlers" and then use it this way:
router := mux.NewRouter()
router.HandleFunc("/config", getConfig).Methods("GET")
router.HandleFunc("/config/emcServer", createEmcServers).Methods("POST")
headersOk := handlers.AllowedHeaders([]string{"X-Requested-With", "Content-Type"})
originsOk := handlers.AllowedOrigins([]string{"*"})
methodsOk := handlers.AllowedMethods([]string{"GET", "HEAD", "POST", "PUT", "OPTIONS"})
log.Fatal(http.ListenAndServe(":" + webServicePort, handlers.CORS(originsOk, headersOk, methodsOk)(router)))
As soon as I executed an Ajax POST request and attaching JSON data to it, Chrome would always add the Content-Type header which was not in my previous AllowedHeaders config.

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