FOSRest OPTIONS request return 405 Method Not Allowed - ember.js

I wrote a REST services with Symfony FOSRestBundle. It work fine with GET request.
Now, I am trying to access with Ember « models" and I get an error message. Indeed, Ember try to access with OPTIONS request (preflight) and It failed with « Request header field Access-Control-Allow-Origin is not allowed by Access-Control-Allow-Headers in preflight response ».
I tried to access the REST service with Postman and I got this error :
with OPTIONS http://myUrl.local/groups : "405 Method Not Allowed »
but it works fine if I call OPTIONS http://myUrl.local/
I use apache under El Capitan (IMac).
I tried to append these lines to /private/etc/apache2/extra/httpd-default.conf :
Header add Access-Control-Allow-Origin "*"
Header add Access-Control-Allow-Headers "origin, content-type"
Header add Access-Control-Allow-Methods "PUT, GET, POST, DELETE, OPTIONS"
I tried to append these lines in directive in my VirtualHost.
Same results in both case.
Is the problem in Symfony or FOSrestBundle.
I need help to understand what is happening. How I can resolve my problem.

I assume that your Ember application is not hosted on the same domain as your Symfony application – it might be an app on your phone? This makes your requests adhere to the CORS protocol (Cross-Origin Resource Sharing).
You have correctly identified the headers you need to set. The reason why it doesn't work is that /groups probably routes to an action similar to this:
<?php
namespace AppBundle\Controller;
class GroupsController
{
public function getGroupsAction()
{} // "get_users" [GET] /users
}
As this action requires the method GET, FOSRestBundle blocks requests of any other method and returns the status code 405 you are getting. That's also why an OPTIONS request to / worked fine – it's not your server blocking it, it's FOSRestBundle.
Use the NelmioCorsBundle to correctly handle preflights. The bundle
Handles CORS preflight OPTIONS requests
Adds CORS headers to your responses
See issue #587 for reference.

Related

Append header in a vue axios request

I have a django backend and a Vue 3 frontend.
For handling some request, my backend needs an 'Id-Client' header in the headers of the request.
Developing my BE everything worked like a charm, but now that I'm writing the FE I'm encountering some issues.
As I said before, I need to append an header to my headers in every request.
So the first step was the following:
// Note that the idClient is dynamic and can change.
this.$axios.setHeader('Id-Client', idClient)
const data = await this.$axios.$get(url)
But I can't get it to work, if I try to send that request, my GET request becomes (I don't know why) a OPTIONS request and I get the error "cross origin resource sharing error: HeaderDisallowedByPreflightResponse"
Instead if I remove the set header
// this.$axios.setHeader('Id-Client', idClient)
const data = await this.$axios.$get(url)
The server just respond me correctly giving me the error that the request is missing the 'Id-Client' in the header.
I also have a few request that don't need the 'Id-client' header and those request work, so I don't think is a CORS problem.
Well but is looks like CORS issue. CORS policies are not triggered by simple requests. By adding custom header, your requests are no longer simple and trigger CORS policies (sending OPTIONS before GET)
Your only option is to configure your backend server to reply to OPTIONS requests with the correct headers - Access-Control-Allow-Origin and Access-Control-Allow-Headers (server telling the browser "yes, im ok to accept particular custom header")
IF (and only if) you are planning to serve your Vue SPA from the same API server in production (same origin), you can avoid similar CORS issues during development by using Webpack Dev server Proxy - your SPA will send API requests to Webpack Dev Server (used for developing SPA) and Proxy will route it to your Django dev server. That way all request from your SPA are to the same origin and you don't need to care about CORS at all...

API Gateway CORS HTTP 415

Okay, I've been all over these interwebs looking for some insight to my issue; I've probably been through over 80 stack overflow threads RE api gateway and such, but none of them seem to help or speak close enough to my issue.
I'm new to API Gateway and cors, but lets see if i can articulate the issue that i am seeing:
Setting up a API gateway proxy to Kinesis firehose hydrating a redshift database. The proxy, firehose, and redshift gateway are up and working when called in isolation, but when called from one of our customer sites, we get an error as follows:
XMLHttpRequest cannot load [api_call_here]. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin [origin_website_here] is therefore not allowed access. The response had HTTP status code 403.
Okay, so that strongly implies that CORS is needed, right? in the console on the resource, enable cors, deploy, new error:
XMLHttpRequest cannot load [api_call_here]. Request header field $cookies is not allowed by Access-Control-Allow-Headers in preflight response.
Ooooooooookay, from the new OPTIONS method added by the enable CORS feature, in integration response, allowed headers, under access control allowed headers add '$Cookies', deploy.
Now i get a new error, very similar to the first error:
XMLHttpRequest cannot load [api_call_here]. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin [origin_website_here] is therefore not allowed access. The response had HTTP status code 415.
Notice the first error had HTTP status code 403, and this third one has status code 415. This is where I'm having issues. If I go into the GET method acting as the proxy method, body mapping templates, I have "When there are no templates defined (recommended)" selected.
Now, I read that when API gateway fails to find a matching template it rejects with a 415 error, so I changed aforementioned option to "When no template matches the request Content-Type header". That made the error disappear, but the data is still not being persisted to redshift when called from the origin. Again, when I call the api directly from postman, insomnia or just a plain old address bar, the records are added nicely.
Opening up chrome and looking at the header i see that the cookie is coming across as text/html.
Regarding the template mapping up there, i have only defined a map for application/json; could that be part of the problem?
Also, the response header as viewed from chrome's console is as follows:
content-length:37
content-type:application/json
date:Wed, 19 Apr 2017 23:43:35 GMT
status:415
via:1.1 [blahblabbleblah].cloudfront.net (CloudFront)
x-amz-cf-id:[blahblabbleblah]
x-amzn-requestid:[blahblabbleblah]
x-cache:Error from cloudfront
I'm relatively new to this so i dont see how cloudfront fits in with this, especially give that it is complaining about media type while the console is complaining about no access-control-allow-origin header.
At any rate, any help as to how to resolve the third error would be most appreciated.
What is the content-type in your requests from the browser? If content-type header isn't specified in the request, then API Gateway assumes "application/json" by default.
Opening up chrome and looking at the header i see that the cookie is coming across as text/html.
I am not sure if you meant that "Content-type" header's value in the request is set to "text/html". If yes, that's the problem. You will either need a matching template, or you will need to pass through by default by choosing "When no template matches the request Content-Type header".
I have some issue with AWS API GW with SQS integration. Problem was that incorrect content type in mapping template, I wrote application/json but correct is application/x-www-form-urlencoded
The request body will never be passed through to the integration.
Requests with a Content-Type header that don't match any templates
will be rejected with a HTTP 415 response.

XMLHttpRequest No 'Access-Control-Allow-Origin' header From SimpleHttpServer

I am writing a rails backend app. I am providing a rest api to the frontend developer who is workng separately. So for time being I have enabled Cross origin resource sharing by adding following in my application.rb:
#todo remove this once ui is integrated into the app. following allows requests from other domains (disble CORS).
config.action_dispatch.default_headers.merge!({
'Access-Control-Allow-Origin' => '*',
'Access-Control-Request-Method' => '*'
});
I am trying to test out the api by using links on a simple HTML page which I am running off of the python SimplHttpServer. The page is being served at http: // localhost:8000/TestPage.html
When I test one of the links (it sends an ajax request using jquery to the backend which at the moment is running locally as well, on http: // localhost : 3000), I get following error:
GET http://localhost:3000/campaigns/my_campaigns?user_email=swapna%40urbancoding.net&user_token=SNa2kPqkm5ENsZMx7yEi
XMLHttpRequest cannot load http://localhost:3000/campaigns/my_campaigns?user_email=xyz.xyz.com&user_token=xyz. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost : 8000' is therefore not allowed access. The response had HTTP status code 500.
What is going on? How can I resolve this?
Turns out the issue was that the url I was sending the request to (http:// localhost:3000/campaigns/my_campaigns) was incorrect. It was matching an action I did not intend it to match. This action was triggering a 'missing template' exception. Somehow this was causing the No 'Access-Control-Allow-Origin' error. Not sure how that happens, but once I fixed my url to go to the intended action, all was well.

Why isn't Ember.js seeing the Access-Control-Allow-Origin header from my server?

My app is an Ember.js front end with a Go API on the server. I created the Ember app using the FixtureAdapter. Now that I have the Go API back end I converted it to RESTAdapter.
When I hit my API directly with the browser, I seem to get the appropriate CORS headers back:
Access-Control-Allow-Credentials:true
Access-Control-Allow-Headers:Origin,x-requested-with
Access-Control-Allow-Methods:PUT,PATCH,GET,POST
Access-Control-Allow-Origin:*
Access-Control-Expose-Headers:Content-Length
However, when my Ember.js app hits the API, I get XMLHttpRequest cannot load https://192.168.59.103:8001/notifications. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://192.168.59.103:9000' is therefore not allowed access..
I don't know how else to see what's going on between Ember and the API. I've read this CORS tutorial and everything seems to be okay on the server end.
I included the bit about x-requested-with because of another Stack Overflow question suggesting that jQuery requests need something different than plain old JavaScript requests.
Your endpoints also need to respond with CORS headers to OPTIONS requests- those will execute before the actual request to make sure that the request is allowed first.
Do you happen to be using Nginx as your reverse proxy for your API? If so, we experienced this same issue. In our case, the problem was that Nginx returns the correct CORS headers just fine for HTTP 200 OK responses, but for any error response, it will fail to add the COR headers and therefore the actual server response gets obscured by the browser complaining that it doesn't have the appropriate CORS headers to render a response.
See https://serverfault.com/a/431580/199943.
Even if you're not using Nginx, try calling your API directly (e.g. using Postman to avoid the CORS restrictions to see what it's returning. If your API is returning anything other than an HTTP 200 OK, that may be why the CORS headers aren't getting added.

AngularJS and Laravel - crossdomain CORS / XHR requests lacking (remember_) cookies

My CORS / XHR requests lacking the remember_xyz cookie in the request headers when i don't use the --disable-web-security option in chrome. If i enable that option the remember_xyz cookie will be included in the request headers and everything is working fine.
As workaround i'm currently sending the auth credentials via basic auth header. But i think that's not the intended or right way.
How can i get that remember cookie included in the request headers?
Edit:
In chrome's network console i can see the following:
(without --disable-web-security option in chrome)
The remember cookie is sent by laravel in the first response headers. But is not included in the next request's headers by angular. Why?
Every request has that OPTIONS preflight request before the actual request fires. Is it possible that the preflight request removes/breaks the cookie somehow?
(with --disable-web-security option in chrome)
The remember cookie is sent by laravel in the first response headers and will be sent in the next request's headers by angular. Everything is fine.
Edit 2:
Is it up to me to include the said cookie out of the response headers into the request headers? When yes, why i don't have to do this with "--disable-web-security" option enabled in chrome?
What i'm doing wrong?
Thank you!
Not sure I'm answering your question directly, but I'll take a stab. You DO need to set certain headers on the client side AND server for CORS.
The client needs to know to send the Cookie headers, or it will strip them out. For jQuery, this means setting the withCredentials parameter in your ajax call. See more info here. This sounds like the issue you are grappling with.
On the server side, you may need to ensure pre-flight requests are setup.
For instance, when I used CORS in Laravel 4, I had a filter to add some headers to each response:
App::after(function($request, $response)
{
// Note that you cannot use wildcard domains when doing CORS with Authorization!
$response->headers->set('Access-Control-Allow-Origin', 'http://dev.domain.local');
$response->headers->set('Access-Control-Allow-Credentials', 'true');
$response->headers->set('Access-Control-Allow-Headers', 'Authorization, X-Requested-With');
});
Within a controller, I also had an OPTIONS request respond for pre-flight requests. An example of that is:
public function optionsComplex()
{
$response = Response::make(null, 200);
$response->headers->set('Allow', 'GET, PUT, DELETE');
$response->headers->set('Access-Control-Allow-Methods', 'GET, PUT, DELETE');
return $response;
}
Hope that helps.