Cross-origin POST request not working even though it is allowed (GET works) - angularjs

I have a weird problem. I am testing this using Angular.js 1.2.15.
I want to send a POST request to a RESTful API backend on another domain (and I want to use $http directly, not $resource).
var mapData = {
'some': 'keys',
'other': 'keys'
}
$http.post(endPoint, mapData);
This is what happens: An OPTIONS request is sent first, with the following request headers:
OPTIONS /api/maps HTTP/1.1
Host: myhost.com
Connection: keep-alive
Access-Control-Request-Method: POST
Origin: http://0.0.0.0:9000
User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Ubuntu Chromium/36.0.1985.125 Chrome/36.0.1985.125 Safari/537.36
Access-Control-Request-Headers: accept, content-type
Accept: */*
Referer: http://0.0.0.0:9000/
Accept-Encoding: gzip,deflate,sdch
Accept-Language: en-US,en;q=0.8
The response clearly shows that requests from other origins and with every method are allowed:
HTTP/1.1 204 No content
Server: Varnish
Connection: keep-alive
Access-Control-Allow-Origin: *
Access-Control-Allow-Credentials: true
Access-Control-Allow-Methods: *
Access-Control-Allow-Headers: DNT,X-Mx-ReqToken,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type
Access-Control-Max-Age: 0
Content-Type: text/plain charset=UTF-8
Accept-Ranges: bytes
Date: Tue, 02 Sep 2014 14:50:16 GMT
X-Varnish: 166874803
Age: 0
Via: 1.1 varnish
Connection: close
Cache-Control: max-age=0, private
X-Varnish-Cache: MISS
But then, the POST request is not even sent by the browser (Chromium 36), i.e. it does not show a POST request in the network tab of the dev console.
Instead, the following is shown in the console:
XMLHttpRequest cannot load http://myhost.com/api/maps. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://0.0.0.0:9000' is therefore not allowed access.
Now, what is totally weird: GET requests to the same API work, and are not preceded by an OPTIONS request (or maybe it is not shown in the network tab).
HTTP/1.1 304 Not Modified
Server: nginx/1.4.7
Content-Type: application/json; charset=utf-8
Status: 200 OK
X-UA-Compatible: IE=Edge,chrome=1
ETag: "baca3b7547fed3377088eb81fe083ff8"
X-Request-Id: b2552dc4fdef2541c841e3d5e12d337e
X-Runtime: 0.110003
X-Rack-Cache: miss
Access-Control-Allow-Origin: *
Access-Control-Allow-Credentials: true
Access-Control-Allow-Methods: GET, POST, PUT, OPTIONS
Access-Control-Allow-Headers: DNT,X-Mx-ReqToken,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type
Accept-Ranges: bytes
Date: Tue, 02 Sep 2014 14:54:31 GMT
X-Varnish: 166874831 166874142
Age: 6223
Via: 1.1 varnish
Connection: keep-alive
Cache-Control: max-age=0, private
X-Varnish-Cache: HIT
I really have no clue what the problem could be here. Is it Angular's implementation? Or is it a misconfiguration on the server? The guys responsible for the API told me it usually works with all their web apps.
I understand that this is a CORS problem and I am by no means an expert when it comes to that, but hey, Access-Control-Allow-Origin: * should do the trick, shouldn't it?
UPDATE: It works when using plain XMLHttpRequest:
var http = new XMLHttpRequest();
var url = endPoint;
var params = JSON.stringify(mapData);
http.open("POST", url, true);
I get a 200 back.
What is the matter here?

Nginx has to be compiled with http://nginx.org/en/docs/http/ngx_http_headers_module.html for Access-Control-Allow-Origin: * to work. Do you have this module installed?
location / {
add_header Access-Control-Allow-Origin *;
}

Related

Random occurrence with preflight response missing allow headers

I've got quite random occurrence with this common error:
OPTIONS https://api.cloudfunctions.net/api/graphql 404
Access to fetch at 'https://api.cloudfunctions.net/api/graphql' from origin 'https://website.com' 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.
What I have is a graphql endpoint with apollo server deployed on Google Cloud Functions and a react client. At some points the client will throw the error on browser but if I try refresh or send the request again 2 or 3 times later it will work.
The preflight request headers being sent:
:authority: api.cloudfunctions.net
:method: OPTIONS
:path: /api/graphql
:scheme: https
accept: */*
accept-encoding: gzip, deflate, br
accept-language: en-US,en;q=0.9,id;q=0.8,ms;q=0.7
access-control-request-headers: content-type
access-control-request-method: POST
origin: https://website.com
referer: https://website.com/
sec-fetch-mode: cors
sec-fetch-site: cross-site
user-agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.88 Safari/537.36
Expected response
access-control-allow-credentials: true
access-control-allow-headers: content-type
access-control-allow-methods: POST,OPTIONS
access-control-allow-origin: https://website.com
alt-svc: quic=":443"; ma=2592000; v="46,43",h3-Q050=":443"; ma=2592000,h3-Q049=":443"; ma=2592000,h3-Q048=":443"; ma=2592000,h3-Q046=":443"; ma=2592000,h3-Q043=":443"; ma=2592000
content-length: 0
content-type: text/html
date: Wed, 08 Jan 2020 00:38:16 GMT
function-execution-id: 84et92k6mvd9
server: Google Frontend
status: 200
vary: Origin, Access-Control-Request-Headers
x-cloud-trace-context: 95d25375171148a66bc629cc41a79d05
x-powered-by: Express
Random failed response
alt-svc: quic=":443"; ma=2592000; v="46,43",h3-Q050=":443"; ma=2592000,h3-Q049=":443"; ma=2592000,h3-Q048=":443"; ma=2592000,h3-Q046=":443"; ma=2592000,h3-Q043=":443"; ma=2592000
cache-control: private
content-encoding: gzip
content-length: 140
content-security-policy: default-src 'none'
content-type: text/html; charset=utf-8
date: Wed, 08 Jan 2020 00:38:05 GMT
function-execution-id: 84etgky3im1k
server: Google Frontend
status: 404
x-cloud-trace-context: 77040d2c72304cad0d645480b6814f7f;o=1
x-content-type-options: nosniff
x-powered-by: Express
Looking at the failed response above kinda make sense that it's missing the access-control-allow-* headers compared to success one, but again I am not sure how that happened.
Here's my cors config:
const corsConfig = {
origin: ['https://website.com', 'http://localhost:3000'],
methods: ['POST', 'OPTIONS'],
credentials: true,
optionsSuccessStatus: 200,
}
const app = express()
app
.use(cors(corsConfig))
.use(...)
...
apolloServer.applyMiddleware({ app, cors: corsConfig })
Based on few suggestions around I have tried different setup but still sometimes the error happens:
set cors: false in applyMiddleware
remove cors
repeat cors as shown above
add app.options('*', cors()) as per doc says
All and all it happens like 1 in 10, sometimes on first request after the user open the site the other times after the user browsing around the site for a while.
I think there might be other middleware that messes up your cors settings.
You can try use a different path for your graphql endpoint, and apply cors only to that path.
apolloServer.applyMiddleware({ app, path: '/graphql', cors: corsConfig });
Alternatively, you can try the express cors middleware and disable the cors from apollo server
I used the apollo-server-cloud-functions package to solve this problem. Just follow the instructions here (https://github.com/apollographql/apollo-server/tree/master/packages/apollo-server-cloud-functions) but instead of using exports.handler = server.createHandler() swap it out for your own function, like this:
exports.api = functions.https.onRequest(
server.createHandler({
cors: {
origin: true,
credentials: true
}
})
);
That solved it for me!

Laravel Cookie not set despite Set-cookie header being present

We're developing a website with a REST Api (frontend in AngularJS 1.6.1, backend in Laravel 5.3).
In order to add CSRF protection, our backend needs to set a backend cookie on the client with a random string. In laravel, we return this response:
response("OK", 200)->cookie("csrf_token", "random_string");
The cookie is clearly being set with the response:
*Request headers*
POST /v1/auth/admin HTTP/1.1
Host: backend.test
Connection: keep-alive
Content-Length: 295
Accept: */*
Origin: http://frontend.test
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36
Content-Type: application/x-www-form-urlencoded; charset=UTF-8
Referer: http://frontend.test/login
Accept-Encoding: gzip, deflate
Accept-Language: it-IT,it;q=0.8,en-US;q=0.6,en;q=0.4
*Response header*
HTTP/1.1 200 OK
Server: nginx/1.11.3
Content-Type: application/json
Transfer-Encoding: chunked
Connection: keep-alive
Access-Control-Allow-Origin: http://frontend.test
Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS, PATCH
Access-Control-Allow-Headers: Origin, Content-Type, Accept, Authorization, X-Requested-With
Access-Control-Allow-Credentials: true
Cache-Control: no-cache
X-RateLimit-Limit: 60
X-RateLimit-Remaining: 59
Date: Mon, 13 Feb 2017 11:46:16 GMT
Set-Cookie: csrf_token=random_string; expires=Sat, 12-Feb-2022 11:46:16 GMT; Max-Age=157680000; path=/; domain=http://backend.test; HttpOnly
However, when I go to the http://backend.test Url, no cookie is set (document.cookie in the console returns null).
The backend cannot see the cookie either: dd($request->cookie("csrf_token") returns null.
It doesn't work even if we omit the domain. Any ideas?
For Angular to send the cookie along with the request in a CORS (Cross Origin Resource Sharing request), you need to set, in your config with $httpProvider injected as a dependency:
.config(function ($httpProvider) {
$httpProvider.defaults.withCredentials = true;
//rest of route code
}
When you use Laravel you do not have to set the csrf cookie by yourself. Laravel automatically does this job for you.
So laravel creates automatically a cookie to store the csrf token. The name of that cookie is "XSRF-TOKEN".

Yeoman,Grunt, AngularJS 404 cannot Post /

I have this little angular app on the frontend which is a food list. So write a food and click submit and it will show the list.
When I add a food I query my backend wich is a sails app at localhost:1337 and it gets updated. The problem is I get redirected to
localhost:9000/#/food and get 404.
This is the faulty request
POST / HTTP/1.1
Host: localhost:9000
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image /webp,*/*;q=0.8
Accept-Encoding: gzip, deflate
Accept-Language: fr-FR,fr;q=0.8,en-US;q=0.6,en;q=0.4
Content-Type: application/x-www-form-urlencoded
Cookie:sails.sid=s%3A8gIjNxaZVE9dMr7nonXJzEaQ9hUcvcHm.Sp0K6ezep%2F7Y%2BV6TivtdRxqiBV 2S1LdH2IDNPWS9Ikk
Origin: http://localhost:9000
Referer: http://localhost:9000/
User-Agent: Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/40.0.2214.115 Safari/537.36
X-DevTools-Emulate-Network-Conditions-Client-Id: 137B2031-138E-4B6B-A3AE- FB8EE96E9015
HTTP/1.1 404 Not Found
Connection: keep-alive
content-length: 14
Content-Type: text/html; charset=utf-8
Date: Mon, 23 Feb 2015 12:21:51 GMT
X-Content-Type-Options: nosniff
The other request that gets code 200 and update the server model looks like this:
OPTIONS /food HTTP/1.1
Host: localhost:1337
Accept: */*
Accept-Encoding: gzip, deflate, sdch
Accept-Language: fr-FR,fr;q=0.8,en-US;q=0.6,en;q=0.4
Access-Control-Request-Headers: accept, content-type
Access-Control-Request-Method: POST
Origin: http://localhost:9000
Referer: http://localhost:9000/
User-Agent: Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/40.0.2214.115 Safari/537.36
X-DevTools-Emulate-Network-Conditions-Client-Id: 137B2031-138E-4B6B-A3AE- FB8EE96E9015
HTTP/1.1 200 OK
Access-Control-Allow-Credentials: true
Access-Control-Allow-Headers: content-type, access-control-allow-origin, authorization,X-Requested-With
Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS, HEAD
Access-Control-Allow-Origin: http://localhost:9000
Allow: GET,POST,PUT,HEAD,DELETE,TRACE,COPY,LOCK,MKCOL,MOVE,PURGE,PROPFIND,PROPPATCH, UNLOCK,REPORT,MKACTIVITY,CHECKOUT,MERGE,M- SEARCH,NOTIFY,SUBSCRIBE,UNSUBSCRIBE,PATCH,SEARCH,CONNECT
Connection: keep-alive
Content-Length: 175
Content-Type: text/html; charset=utf-8
Date: Mon, 23 Feb 2015 12:21:51 GMT
set-cookie: sails.sid=s%3A_kBdyRZgZ23Gh9YLkZfWBgnMody- jq-S.IY71%2BhJiBxTd19YIG2tgS2EOn1LPT%2BD9QAEQWtVB%2FbE; Path=/; HttpOnly
X-Powered-By: Sails <sailsjs.org>
At first I was looking at sails but I have CORS enabled and everything just like this:
https://github.com/tarlepp/angular-sailsjs-boilerplate/blob/master/backend/config/cors.js
So maybe it's more an angular issue. The request that fails is from the frontend to itself so just a redirect on itself when it has been updated on the server. I don't get why the request is denied...
If you want to take a look at the code:
http://okamuuu.hatenablog.com/entry/2014/04/10/135240
Issues seem the same as this Yeoman, Grunt, AngularJS and error 404 on POST form but that doesn't help me
Well, apparently your request is going to the port 9000:
Host: localhost:9000
Yet you said your app is running at port 1337.
So, in your $http requests, you need to specify the port. Otherwise, it will use the port your browser is currently connected to (9000) and there's no app there!
So, instead of
$http.get('/someUrl')
Try
$http.get('http://localhost:1337/someUrl')

How to enable Angular $http redirect on CORS

I have a node/express aplication with CORS enabled
When I do POST /login to my app does a redirect to /failure or /success
but always a i get a
XMLHttpRequest cannot load http://exampledomain.com/login. The request was redirected to 'http://exampledomain.com/success', which is disallowed for cross-origin requests that require preflight.
the $http do two requests to the server
OPTIONS request
HTTP/1.1 204 No Content
Access-Control-Allow-Origin: http://otherdomain.com
Vary: Origin
Access-Control-Allow-Credentials: true
Access-Control-Allow-Methods: GET,PUT,POST,PATCH,DELETE
Access-Control-Allow-Headers: accept, content-type
Connection: keep-alive
Options response
HTTP/1.1 204 No Content
Access-Control-Allow-Origin: http://otherdomain.com
Vary: Origin
Access-Control-Allow-Credentials: true
Access-Control-Allow-Methods: GET,PUT,POST,PATCH,DELETE
Access-Control-Allow-Headers: accept, content-type
Connection: keep-alive
POST request
POST /admin/login HTTP/1.1
Host: exampledomain.com
Connection: keep-alive
Content-Length: 43
Accept: application/json, text/plain, */*
Origin: http://otherdomain.com
User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2267.0 Safari/537.36
Content-Type: application/json;charset=UTF-8
Referer: http://otherdomain.com
Accept-Encoding: gzip, deflate
Accept-Language: es-419,es;q=0.8
POST response
HTTP/1.1 302 Moved Temporarily
Vary: X-HTTP-Method-Override, Origin, Accept
Access-Control-Allow-Origin: http://otherdomain.com
Access-Control-Allow-Credentials: true
Location: /success
Content-Type: text/plain; charset=utf-8
Content-Length: 45
set-cookie: cookie-data; Path=/; HttpOnly
Connection: keep-alive
I think the headers are correct but something is missing about the Location header. Can help me with this
I'm doing the request with $http like follows
$http.defaults.useXDomain = true;
$http.post('http://exampledomain/login', {
username: 'user',
password: 'pass'
}).success(...).error(...)
but the success is never called
CORS is not enabled for http://exampledomain.com, thus no requests can be made to it. In fact the browser does a preflight check and since it fails the requests are not actually sent to the server at all.
The only way to change this is to enable CORS on the server for your domain.

AngularJS not sending request after CORS preflight response

Using AngularJS to call RESTFUL APIs.
When using Chrome browser on IOS, the CORS preflight request's (OPTIONS request's) Accept header gets set to */*,image/webp. The response comes back fine, but the actual GET request never gets sent. As you can see in the response, the Content-Type header gets set to image/webp, which I suspect is causing the problem in AngularJS from moving forward with the GET request.
Is my assumption correct? If so, is the solution to force the server to set the Content-Type to something else ?
Full request headers:
OPTIONS http://www.example.com:8080/resourceABC HTTP/1.1
Host: www.example.com:8080
Connection: keep-alive
Access-Control-Request-Headers: accept, authorization, origin
Access-Control-Request-Method: GET
Origin: http://www.example.com
Accept: */*,image/webp
Referer: http://www.example.com/
User-Agent: Mozilla/5.0 (iPhone; CPU iPhone OS 8_1 like Mac OS X) AppleWebKit/600.1.4 (KHTML, like Gecko) CriOS/38.0.2125.67 Mobile/12B411 Safari/600.1.4
Accept-Encoding: gzip,deflate,sdch
Accept-Language: en-US,en;q=0.8
Full response headers:
HTTP/1.1 200 OK
Server: Apache-Coyote/1.1
Allow: GET,OPTIONS,HEAD
Access-Control-Allow-Origin: *
Access-Control-Allow-Credentials: true
Access-Control-Allow-Methods: GET, POST, PUT, OPTIONS
Access-Control-Allow-Headers: X-HTTP-Method-Override, Content-Type, x-requested-with, authorization, accept
Access-Control-Max-Age: 3600
Content-Type: image/webp
Content-Length: 0
Date: Wed, 29 Oct 2014 19:26:37 GMT
Hy.
I just had the same thing here accessing a REST-Service on a different domain from AngularJS-Service.
Examining the request-headers sent to my REST-Service to see if I do allow everything that is requested from the client lead mit to the following:
Setting 'Access-Control-Allow-Headers' in a way to make sure it contains all items in 'Access-Control-Request-Headers' solved it for me.
Marc I see that in your 'Access-Control-Request-Headers' the header "origin" is requested but in your "Access-Control-Allow-Headers" it's missing.
Sending the following Response-Headers works in my case (appkey is my internal auth-key in header):
Access-Control-Allow-Origin: *
Access-Control-Allow-Methods: *
Access-Control-Allow-Headers: appkey,content-type
Hope this is clear and it helps.
Best regards,
Christian
P.S.: "Access-Control-Allow-Headers: *" did not work in my case
UPDATE:
To allow Form-Submit via POST-Request I had to add 'content-type' to 'Access-Control-Allow-Headers'

Resources