I'm trying to create a get request using Fetch. The request looks like this:
fetch('https://requestb.in/14ikb6j1', {
method: 'get',
headers: {
'Authorization': 'Token token=xxxxx'
}});
If I make this request to my own server, it fails on the options request every time. I cannot figure out why.
If I make this request to requestbin, there is an options request first. However, after receiving the options response, the actual get request is never made.
This is what requestbin received:
OPTIONS /14ikb6j1
HEADERS
Referer: http://localhost:9000/
Host: requestb.in
Total-Route-Time: 0
Via: 1.1 vegur
Accept-Encoding: gzip
Cf-Visitor: {"scheme":"https"}
Cf-Ipcountry: NL
Cf-Ray: 36edd35d1cad2b28-AMS
Cf-Connecting-Ip: 37.153.231.90
Connection: close
User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36
Accept: */*
Connect-Time: 1
Access-Control-Request-Method: GET
Content-Length: 0
Accept-Language: nl-NL,nl;q=0.8,en-US;q=0.6,en;q=0.4
X-Request-Id: 69b120c1-0f18-454b-a7fd-91f082252a06
Access-Control-Request-Headers: authorization
Origin: http://localhost:9000
This is what chrome logs:
The strangest thing is, I get a 200 - OK status as result. The console however, still logs this:
Fetch API cannot load https://requestb.in/14ikb6j1. 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:9000' is therefore not allowed
access. If an opaque response serves your needs, set the request's
mode to 'no-cors' to fetch the resource with CORS disabled.
:9000/#/branching:1 Uncaught (in promise) TypeError: Failed to fetch
But if I make this request using Postman it does work:
GET /14ikb6j1
HEADERS
Cf-Ipcountry: NL
Cf-Ray: 36eddb797ebf7223-AMS
Authorization: Token token=xxxx
User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36
Total-Route-Time: 0
Via: 1.1 vegur
Connection: close
Cf-Connecting-Ip: 37.153.231.90
Connect-Time: 0
Accept-Language: nl-NL,nl;q=0.8,en-US;q=0.6,en;q=0.4
Postman-Token: 57486701-6f9a-4aab-be1b-776f0d376920
Accept: */*
Host: requestb.in
X-Request-Id: 73a7a35e-0d89-41fd-b760-2aa952349871
Accept-Encoding: gzip
Cf-Visitor: {"scheme":"https"}
Cache-Control: no-cache
How can I make this get request with authentication headers work?
This is probably a CORS problem. The server you are seinding the request to doesn't allow requests from a different domain.
Check your browser console and look for errors. You might find somehting like this:
Fetch API cannot load https://requestb.in/14ikb6j1. Response to
preflight request doesn't pass access control check: No
'Access-Control-Allow-Origin' header is present on the requested
resource. Origin 'https://localhost:9000' is therefore not allowed
access. If an opaque response serves your needs, set the request's
mode to 'no-cors' to fetch the resource with CORS disabled.
Related
I have an application (React SPA) that calls a bunch of servers on different subdomains of the application domain, i.e.:
the web app sits at foo.bar.com,
and talks to api.foo.bar.com and media.foo.bar.com.
When accessing api.foo.bar.com, I get an error from the browser (be it Edge, Chrome, or Firefox) telling me that the origin (foo.bar.com) is different from the value of the Access-Control-Allow-Origin response header. However, by inspection of the response, they are the same:
(I unfortunately have to obfuscate the address.)
Those apps are hosted on Kubernetes; the ingress is NGINX, and it's is not providing CORS (cors-enabled annotation is false). Both applications (api and media) are Express apps, and both have the same CORS configuration allowing the specific origin.
I'm wondering if this has something to do with the redirect - the call to the media... endpoint returns a redirect (302) whose Location is a api... address.
Other than that, I have no clue what could be wrong. Something is, for sure, because all browsers agree that my request should be blocked (on account of the origin).
In all cases, I've checked the address multiple times for typos, ending forward-slashes, etc. I've called OPTIONS on those endpoints with cURL and Postman, using all headers or just a few. They always answer the correct address.
Additional information, as requested:
Preflight request:
OPTIONS /media/1.0.0/rtsp/hls?feedUrl=https%3A%2F%2Flive.monuv.com.br%2Fa1%2F14298.stream%2Fstr27%2Fchunklist.m3u8%3Fm_hash%3DkhV_hCnKG3nhaNCFaYZxBnoMz-99idQVHiQh80ADW78%253D HTTP/2
Host: media.aiXXXXXXXXXXXXXX.com
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:93.0) Gecko/20100101 Firefox/93.0
Accept: */*
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate, br
Access-Control-Request-Method: GET
Access-Control-Request-Headers: feedurl
Referer: https://aiXXXXXXXXXXXXXXXX.com/
Origin: https://aiXXXXXXXXXXXXXXXX.com
DNT: 1
Connection: keep-alive
Sec-Fetch-Dest: empty
Sec-Fetch-Mode: cors
Sec-Fetch-Site: same-site
Pragma: no-cache
Cache-Control: no-cache
TE: trailers
Preflight response:
HTTP/2 204 No Content
date: Fri, 08 Oct 2021 13:33:10 GMT
x-powered-by: Express
access-control-allow-origin: https://aiXXXXXXXXXXXXXXXXXX.com
vary: Origin
access-control-allow-credentials: true
access-control-allow-methods: GET,HEAD,PUT,PATCH,POST,DELETE
access-control-allow-headers: Content-Type, feedUrl
strict-transport-security: max-age=15724800; includeSubDomains
X-Firefox-Spdy: h2
Request
The preflight passes, and the browsers starts a "flight" request:
GET /media/1.0.0/rtsp/hls?feedUrl=https%3A%2F%2Flive.monuv.com.br%2Fa1%2F14298.stream%2Fstr27%2Fchunklist.m3u8%3Fm_hash%3DkhV_hCnKG3nhaNCFaYZxBnoMz-99idQVHiQh80ADW78%253D HTTP/2
Host: media.aiXXXXXXXXXXXXXXXXXXXXX.com
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:93.0) Gecko/20100101 Firefox/93.0
Accept: */*
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate, br
feedUrl: https://live.monuv.com.br/a1/14298.stream/str27/chunklist.m3u8?m_hash=khV_hCnKG3nhaNCFaYZxBnoMz-99idQVHiQh80ADW78%3D
Origin: https://aiXXXXXXXXXXXXXXXX.com
DNT: 1
Connection: keep-alive
Referer: https://aiXXXXXXXXXXXXXXXXX.com/
Cookie: ory_kratos_session=MTYzMzYzODY1OHxEdi1CQkFFQ180SUFBUkFCRUFBQVJfLUNBQUVHYzNSeWFXNW5EQThBRFhObGMzTnBiXXXXXXXXXXXXYVc1bkRDSUFJSHBtUWxsaWFsVlJhWGRTVGxSMmIzZHRkbTFqYm5CUlRWVkdkelpPWkRoWnXXXTyqwgK-0Pe0qtZHjNhfU-YoASjg3istMZi672swQ==
Sec-Fetch-Dest: empty
Sec-Fetch-Mode: cors
Sec-Fetch-Site: same-site
Pragma: no-cache
Cache-Control: no-cache
TE: trailers
Response
HTTP/2 302 Found
date: Fri, 08 Oct 2021 13:33:10 GMT
content-type: text/plain; charset=utf-8
content-length: 129
location: https://api.aiXXXXXXXXXXXXXXXXXX.com/media/1.0.0/hls/streams/19dd149d-f551-4093-b2aa-e5558388d545/hls.m3u8
x-powered-by: Express
access-control-allow-origin: https://aiXXXXXXXXXXXXXXXX.com
vary: Origin, Accept
access-control-allow-credentials: true
strict-transport-security: max-age=15724800; includeSubDomains
X-Firefox-Spdy: h2
At this response, the browser fails saying that the origin don't match the access-control-allow-origin.
(the first image was from Edge, since the log was more clear; this log is from Firefox)
Problem
The error message—I'm using dummy URLs and origins below—from the browser can be a bit confusing:
Access to XMLHttpRequest at 'https://api.example.com/' (redirected from 'https://media.example.com/') from origin 'https://example.com' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: The 'Access-Control-Allow-Origin' header has a value 'https://example.com' that is not equal to the supplied origin.
The key here is that, as sideshowbarker hinted at in his comment, because your first preflighted request to https://media.example.com/ responds with a cross-origin redirect to https://api.example.com/, the browser performs another whole CORS access-control check for that resource. However, because the redirect resulting from the first preflighted request happens to be cross-origin, the browser sets the origin of the second preflight request (which the error message refers to as the "supplied origin"), not as https://example.com, but as the null origin!
Here's a rundown of what is likely happening:
Because https://api.example.com likely doesn't (and shouldn't!) allow the null, the second access-control check fails and you get that annoying CORS error.
Solution
Resist the temptation to allow the null origin on https://api.example.com/, as doing so has serious security ramifications: it amount to voiding the protection that the Same-Origin Policy provides.
Instead, you should get rid of that redirect from https://media.example.com/ to https://api.example.com/ and make your frontend request the https://api.example.com/ resource directly.
Alternatively, if you cannot completely get rid of the redirect but you can change its destination, make it a same-origin redirect (from somewhere https://media.example.org to elsewhere on https://media.example.org).
I have a JavaScript application let's say that it is deployed on portal.example.com.
That includes a <script> tag that loads source that is served from assets.example.com.
That JavaScript file makes an HTTP request to an API on admin.example.com
This API request is erroring due to CORS pre-flight failing.
Failed to load http://admin.example.com/v0/user/navigation: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://portal.example.com' is therefore not allowed access.
The actual OPTIONS request is as below
OPTIONS /v0/user/navigation HTTP/1.1
Host: admin.example.com
Connection: keep-alive
Access-Control-Request-Method: GET
Origin: http://portal.example.com
User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.84 Safari/537.36
Access-Control-Request-Headers: authorization,x-correlation-id,x-user-domain
Accept: */*
Accept-Encoding: gzip, deflate
Accept-Language: en-US,en;q=0.9,en-GB;q=0.8
The actual OPTIONS response is as below
HTTP/1.1 200
Allow: GET
Access-Control-Allow-Headers: authorization,x-correlation-id,x-user-domain
Access-Control-Allow-Methods: GET
Access-Control-Allow-Origin: http://portal.example.com
Vary: Origin
Content-Length: 0
Date: Tue, 20 Feb 2018 12:12:19 GMT
Set-Cookie: 97d2c19dadc3933a73dce9bec0748df1=5a15895c5e0f5b526c177132cb4aa666; path=/; HttpOnly
Cache-control: private
X-RBT-SCAR: 10.127.48.7:777511903:1000
I think the issue is because the request is actually coming from a script served from assets.example.com is making the request. So I should be returning Access-Control-Allow-Origin: http://assets.example.com in the OPTIONS response. However, I have followed the advice of W3C.
The Access-Control-Allow-Origin header indicates whether a resource can be shared based by returning the value of the Origin request header, "*", or "null" in the response.
So am I misunderstanding CORS, or is the browser sending the Origin of the main executing URL and not the URL of the script making the request?
UPDATED
GET response
HTTP/1.1 200
X-Correlation-Id: 8978b245-081a-4c4a-b4c9-73f2920ab55c
Content-Type: application/vnd.example+json
Transfer-Encoding: chunked
Date: Tue, 20 Feb 2018 13:22:39 GMT
Set-Cookie: 97d2c19dadc3933a73dce9bec0748df1=dc4e3543c3071d752959e7176c5e4d29; path=/; HttpOnly
Cache-control: private
X-RBT-SCAR: 10.127.48.7:778160108:2000
No 'Access-Control-Allow-Origin' header is present on the requested resource.
That means that 'Access-Control-Allow-Origin' header is missing, not that your domain is not allowed.
If you didn't have permission, you would see something like
The 'Access-Control-Allow-Origin' header has a value 'http://www.example.com' that is not equal to the supplied origin.
So, to solve your problem you need to configure your GET response to provide the necessary CORS headers as well as the OPTIONS response.
In your edited question the GET response headers doesn't provide anything for the Access-Control-* so that's why you get the error!
Your CORS preflight is not failing - you're getting a 200 response and all the required CORS response headers...
However, you're not returning any of the CORS response headers in the GET response - that is what's failing. At a minimum, you need to return a Access-Control-Allow-Origin response header which matches the one returned in the OPTIONS response.
So just include this in your GET response and you'll be fine:
Access-Control-Allow-Origin: http://portal.example.com
Finally, the Origin request header is added by the browser, and trust me - it's correct. But it really doesn't matter what value is sent, since all that is required is that the Access-Control-Allow-Origin response header matches the Origin request header (either by having a value of '*' or exactly matching the Origin value).
Using fetch api in the client browser, I am not having issues with GET or POST, but I am having issues with fetch and DELETE. Its seems to change the DELETE request method to OPTIONS.
Most of the research shows to be a cors issues, but with me I have the cors issues covered.
I am not sure if this is a valid fetch spec api link but it shows:
A CORS-safe listed method is a method that is GET, HEAD, or POST.
I am not sure if this means I can not use DELETE on fetch with cors and this is why I am having issues?
browser code:
var request =
new Request(url, {
credentials: 'include',
mode: 'cors',
method: 'DELETE'
});
return fetch(request)
.then(this.fetchError.bind(this))
.then(this.json)
.then((response)=> {
this.set(`uploadState.${index}.value`, false);
})
.catch((e) => {
console.log(e);
});
},
chrome network tab:
Request URL:http://72.12.4.3:9000/api/v1/listings/3/47/image-3-47-1492565415145.jpeg
Request Method:OPTIONS
Status Code:401 Unauthorized
Remote Address:72.12.4.3:9000
Response Headers
view source
Access-Control-Allow-Credentials:true
Access-Control-Allow-Headers:true
Access-Control-Allow-Methods:POST, GET, OPTIONS, DELETE
Access-Control-Allow-Origin:http://72.12.4.3:8000
Connection:keep-alive
Content-Length:25
Content-Type:application/json; charset=utf-8
Date:Wed, 19 Apr 2017 01:36:07 GMT
ETag:W/"19-9NCRiMyz+z1Bt6fGQfcxA"
X-Powered-By:Express
Request Headers
view source
Accept:*/*
Accept-Encoding:gzip, deflate, sdch
Accept-Language:en-US,en;q=0.8
Access-Control-Request-Headers:
Access-Control-Request-Method:DELETE
Cache-Control:no-cache
Connection:keep-alive
Host:72.12.4.3:9000
If-None-Match:W/"19-9NCRiMyz+z1Bt6fGQfcxA"
Origin:http://72.12.4.3:8000
Pragma:no-cache
Referer:http://72.12.4.3:8000/
User-Agent:Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36
The OPTIONS request is expected and basically is the mechanism that the browser uses to check if the request DELETE in this case is allowed.
The OPTIONS request seems to get a 401 Unauthorized response from your server. This would indeed cause the request to fail. Respond with 200 OK instead.
As an aside, the header Access-Control-Allow-Headers: is wrong, but this shouldn't affect anything.
I am trying to use JavaScripts Fetch() API to send an AJAX request to my PHP OAuth server.
My issue is that I need to send a Request header Authorization with
'Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsImp0aSI6IjM3MWFjZTRiZWE1NmViZDQ5YzQ1OTFkMmJiY2E4NGMwOTM2N2JiMjZmNjZiMmJkOTkxZmE3YmU0NTJjYWZmODBkMmZlYmJhYjFjNzMyMmM1In0.eyJhdWQiOiIxIiwianRpIjoiMzcxYWNlNGJlYTU2ZWJkNDljNDU5MWQyYmJjYTg0YzA5MzY3YmIyNmY2NmIyYmQ5OTFmYTdiZTQ1MmNhZmY4MGQyZmViYmFiMWM3MzIyYzUiLCJpYXQiOjE0ODA1NTE5NzIsIm5iZiI6MTQ4MDU1MTk3MiwiZXhwIjoxNTA3NzY3OTcyLCJzdWIiOiI0Iiwic2NvcGVzIjpbImNydWQtYm9va21hcmstY29sbGVjdGlvbnMiLCJjcnVkLWJvb2ttYXJrLXRhZ3MiLCJjcnVkLWJvb2ttYXJrcyJdfQ.YZWbwDXx4gsUtmvLP1GOY2XUnQ5MC030ymfoV6AYjgQMOqKnsmwrsYrTv5q6MVzo50_SMLipyA9t2VgpZkXj6tOdzA-v9idGnV8JVy-GZeceRlhgl7mpnAe1icI5P62mfhHQiyAdF2cfH6OKsy3ONzyzXRw1_pm-5o_qzcNbUGIATnKr5jXbYElRZZlh7-TUBQ2aSnEsu_fOR2rX5zZ_2dhpAMyE5GOK-UODhjs9PQVLXEEtnlzXyRIdjv-2YTuwJzLryHoooP4N5SncvkBlA6mk0IXVnVnJAMkomnkulofmn1k1niK6Dnzk8OANjbi_uPNbj4W2EtHA0tENNKDfAJ9maiHQZgmpWVk_rkKPrw04BogJNq682mgZhRwYjMM8tD7Rzmrb1DRI8_dM60O5AL5Nm5sxXzKd946OGmMLSQ_OnvAXsAN52KdnlQNW2RzMkFErdrXADMf1g1u7WjH-yo7G9wf-2QMVt8ejrWIbj3_7eBUHIWc4VYg_-IzFMkXl_WXKh12n1RnB62nvyz0IQ5aHbNP0_jIFZixHs0CjuNKikoWguEWfRL78eb2cTyxYMn3E2Yh31RMMaJzF1mM-we05D9WPyQUPKNMuIUQVVRI4GOvny9IJUuGbjcQVLsA-EMbXTBcf9LdRo62gQTNyeCYIshgw3MhX9OazDGK7Xks'
This is the code I have right now....
var app = {
init: function() {
this.apitest();
},
apitest: function() {
var request = new Request('http://bookmarkapi.dev/api/user', {
method: 'GET',
mode: 'no-cors',
headers: new Headers({
'Content-Type': 'application/json',
'Accept': 'application/json',
'Authorization': 'Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsImp0aSI6IjM3MWFjZTRiZWE1NmViZDQ5YzQ1OTFkMmJiY2E4NGMwOTM2N2JiMjZmNjZiMmJkOTkxZmE3YmU0NTJjYWZmODBkMmZlYmJhYjFjNzMyMmM1In0.eyJhdWQiOiIxIiwianRpIjoiMzcxYWNlNGJlYTU2ZWJkNDljNDU5MWQyYmJjYTg0YzA5MzY3YmIyNmY2NmIyYmQ5OTFmYTdiZTQ1MmNhZmY4MGQyZmViYmFiMWM3MzIyYzUiLCJpYXQiOjE0ODA1NTE5NzIsIm5iZiI6MTQ4MDU1MTk3MiwiZXhwIjoxNTA3NzY3OTcyLCJzdWIiOiI0Iiwic2NvcGVzIjpbImNydWQtYm9va21hcmstY29sbGVjdGlvbnMiLCJjcnVkLWJvb2ttYXJrLXRhZ3MiLCJjcnVkLWJvb2ttYXJrcyJdfQ.YZWbwDXx4gsUtmvLP1GOY2XUnQ5MC030ymfoV6AYjgQMOqKnsmwrsYrTv5q6MVzo50_SMLipyA9t2VgpZkXj6tOdzA-v9idGnV8JVy-GZeceRlhgl7mpnAe1icI5P62mfhHQiyAdF2cfH6OKsy3ONzyzXRw1_pm-5o_qzcNbUGIATnKr5jXbYElRZZlh7-TUBQ2aSnEsu_fOR2rX5zZ_2dhpAMyE5GOK-UODhjs9PQVLXEEtnlzXyRIdjv-2YTuwJzLryHoooP4N5SncvkBlA6mk0IXVnVnJAMkomnkulofmn1k1niK6Dnzk8OANjbi_uPNbj4W2EtHA0tENNKDfAJ9maiHQZgmpWVk_rkKPrw04BogJNq682mgZhRwYjMM8tD7Rzmrb1DRI8_dM60O5AL5Nm5sxXzKd946OGmMLSQ_OnvAXsAN52KdnlQNW2RzMkFErdrXADMf1g1u7WjH-yo7G9wf-2QMVt8ejrWIbj3_7eBUHIWc4VYg_-IzFMkXl_WXKh12n1RnB62nvyz0IQ5aHbNP0_jIFZixHs0CjuNKikoWguEWfRL78eb2cTyxYMn3E2Yh31RMMaJzF1mM-we05D9WPyQUPKNMuIUQVVRI4GOvny9IJUuGbjcQVLsA-EMbXTBcf9LdRo62gQTNyeCYIshgw3MhX9OazDGK7Xks'
})
});
return fetch(request).then(app.checkStatus).then(app.parseJSON);
},
checkStatus: function(response) {
if (response.status >= 200 && response.status < 300) {
return response
} else {
var error = new Error(response.statusText)
error.response = response
throw error
}
},
parseJSON: function(response) {
return response.json()
},
};
The result of this in Google Chrome Dev Tools Network tab under Headers is this:
General:
Request URL:http://bookmarkapi.dev/api/user
Request Method:GET
Status Code:401 Unauthorized
Remote Address:127.0.0.1:80
Response Headers:
HTTP/1.1 401 Unauthorized
Date: Thu, 01 Dec 2016 00:41:43 GMT
Server: Apache/2.4.10 (Win32) OpenSSL/1.0.1i PHP/5.6.23
X-Powered-By: PHP/5.6.23
Cache-Control: no-cache
Content-Length: 28
Keep-Alive: timeout=5, max=99
Connection: Keep-Alive
Content-Type: application/json
Request Headers:
GET /api/user HTTP/1.1
Host: bookmarkapi.dev
Connection: keep-alive
Pragma: no-cache
Cache-Control: no-cache
accept: application/json
User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.99 Safari/537.36
Referer: http://localhost/labs/webdevapp/tmp/tools/lab/manage_bookmark_list_tags.html
Accept-Encoding: gzip, deflate, sdch
Accept-Language: en-US,en;q=0.8
These 2 images below show the same exact data being sent to the URL using the app Postman and everything works great as the correct headers get sent so my server responds correctly.
This image shows my server returning the authenticated resources and the headers:
Access-Control-Allow-Headers →Authorization
Access-Control-Allow-Methods →GET, POST, PUT, DELETE, OPTIONS
Access-Control-Allow-Origin →*
These headers are not shown when making a request with JS Fetch() in Chrome or Firefox!
Also when I use a plugin to send custom headers in my browsers, it works correctly so the issue seems to be with the Fetch() function not send my custom headers.
Any ideas how I can get JS Fetch() to send my custom headers with my request?
From all the articles I have seen on using Fetch, it seems I have done it correctly however it does not send the headers in Google Chrome or Firefox so apparently it is not working! I have even tried adding a Fetch Pollyfil just to be on the safe side with no luck!
I finally resolved the issue. The browser request was actually the CORS preflight request in which my server was not returning the correct data so that is why fetch never sent my headers.
I now use this Laravel package https://github.com/barryvdh/laravel-cors to add cors support to a PHP laravel app and al is working great!
You are using mode: 'no-cors', this is prevent browser to sending OPTIONS request before GET. With OPTIONS request browser "notifies the server that when the actual request is sent, it will be sent with SOME custom headers. The server now has an opportunity to determine whether it wishes to accept a request under some circumstances.".
Mozilla HTTP OPTIONS method
if you do not implement that circumstances, your request will die at OPTIONS.
This is my trouble:
With $http I'm trying to make a request. This is the response:
No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8383' is therefore not allowed access.
I just enable all that I need to make CORS request. This is on my server:
httpResponse.setHeader("Access-Control-Allow-Origin", "*");
httpResponse.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
httpResponse.setHeader("Access-Control-Max-Age", "3600");
httpResponse.setHeader("Access-Control-Allow-Headers", "x-requested-with, bbtoken, CUSTOM_AUTH_TOKEN, Authorization");
httpResponse.setHeader("Access-Control-Expose-Headers", "CUSTOM_AUTH_TOKEN");
This is the code from Angular:
$http({
method: 'GET',
url: 'http://www.myurl\:8080/mypath/myservice',
headers: {
CUSTOM_AUTH_TOKEN: SessionService.currentUser.token
}
})
.success(function(data, status, headers, config) {
successCallback(data);
})
.error(function(data, status, headers, config) {
console.error(data);
});
But I found an infamous 401 Auth Error.
If I try with cURL or RestConsole (chrome), all is ok... I cannot understand the mistake!
Thanks!
UPDATE
This is the source request header
OPTIONS /mypath/blabla HTTP/1.1
Host: myhost
Connection: keep-alive
Cache-Control: no-cache
Pragma: no-cache
Access-Control-Request-Method: GET
Origin: http://localhost:8383
User-Agent: Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/35.0.1916.114 Safari/537.36
Access-Control-Request-Headers: custom_auth_token
Accept: */*
Referer: http://localhost:8383/index.html
Accept-Encoding: gzip,deflate,sdch
Accept-Language: it
UPDATE WITH RESPONSE
HTTP/1.1 401 Unauthorized
Server: Apache-Coyote/1.1
WWW-Authenticate: Basic realm="Restricted Service"
Content-Type: text/html;charset=utf-8
Content-Language: en
Content-Length: 1079
Date: Sun, 08 Jun 2014 08:08:32 GMT
You are adding a custom HTTP request header to the request, this prevents the request from being simple and makes it preflighted.
Before the browser will make the GET request, it will make an OPTIONS request to ask if the extra header is acceptable.
You need to set up your server so it will respond with suitable CORS headers to the OPTIONS request as well as the GET request.
Solved: The problem came from by Spring Security. A nonsense configuration about security, needs authentication (by custom filter) on all request. OPTION included. By for HTTP standards, the headers inside the OPTION do not contain values, but only name (of the headers)
This is the solution for my trouble:
<intercept-url pattern="/**" access="permitAll" method="OPTIONS" requires-channel="any"/>