Failed to load, Response for preflight has invalid HTTP status code 500 - spring

I have http get method called by client side to the server, but when ran it, the method is OPTIONS, here is the output i am seeing in Chrome Dev tools, for the GET Method,
Request URL: http://localhost:9090/area
Request Method: OPTIONS
Status Code: 500
Remote Address: [::1]:9090
Referrer Policy: no-referrer-when-downgrade
Response headers,
Access-Control-Allow-Credentials: true
Access-Control-Allow-Headers: authorization, content-type
Access-Control-Allow-Methods: GET
Access-Control-Allow-Origin: http://localhost:4201
Allow: GET, HEAD, POST, PUT, DELETE, TRACE, OPTIONS, PATCH
Cache-Control: no-cache, no-store, max-age=0, must-revalidate
Connection: close
Content-Length: 0
Date: Tue, 20 Mar 2018 18:49:59 GMT
Expires: 0
Pragma: no-cache
Vary: Origin
X-Content-Type-Options: nosniff
X-Frame-Options: DENY
X-XSS-Protection: 1; mode=block
and Request headers are,
Accept: */*
Accept-Encoding: gzip, deflate, br
Accept-Language: en-US,en;q=0.9
Access-Control-Request-Headers: authorization,content-type
Access-Control-Request-Method: GET
Connection: keep-alive
Host: localhost:9090
Origin: http://localhost:4201
User-Agent: Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.162 Safari/537.36
Why the GET method is not getting called, i know there are already some answers here, but i did not understand well, can some one please help me for clear understandig? Thank You in advance.

The OPTIONS request is what is called a preflight request from the browser. In a simple way is basically the browser sending an initial request to the server asking for permission to then do a GET or POST or any other verb. This happens whenever a request needs permissions to be executed. If the server replies saying you have permissions to run the request you intend to, it will then perform the initial request (GET in this case). If the OPTIONS request is denied, it will not execute any subsequent request. You can see it as a way of testing the waters for requests :)
The reasons to be denied may be several. You might not have the correct headers, you might be missing authentication or authentication token, and so on.
From what I can see on your requests you are doing the requests from localhost to localhost. That will cause you problems with CORS.
Here’s a link on how to configure CORS for spring ( the server you said you are using in the comments below )

Related

Server response to ajax call with 200 but on browser I get error 400 on Safari

I have a strange behavior on a WordPress site. It is working just fine but several users (on safari) reported seeing error 400. While testing with safari I manage to reproduce the problem with changing the user-agent of the browser. Then I started getting error 400 on each ajax call. I've checked the access.log and all request to admin-ajax.php where served with status 200. But when I check the inspector in Safari, the same ajax request got status 400. And this is happening with each and every single ajax request on every page of the site. I've tried to log out/log in, cleared all cookies, cache and etc. but the error was still there.
The site uses ClouldFlare, so I went there and checked all the security and firewall rules, I didn't found my IP blocked anywhere.
So now the question is how a response with code 200 becomes 400?
Here is also the request and response of ajax call:
Summary
URL: https://www.example.com.com/wp-admin/admin-ajax.php
Status: 400
Source: Local Override
Address: yyy.yyy.yyy.yyy:zzz
Initiator: some-script.min.js:1:2080
Request
:method: POST
:scheme: https
:authority: www.example.com.com
:path: /wp-admin/admin-ajax.php
Accept: application/json, text/plain, */*
Content-Type: application/x-www-form-urlencoded
Origin: https://www.example.com.com
Cookie: some-cookies
Content-Length: 88
Accept-Language: en-us
Host: www.example.com.com
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/14.0.3 Safari/605.1.15
Referer: https://www.example.com.com/units/main/
Accept-Encoding: gzip, deflate, br
Connection: keep-alive
Response
:status: 400
Date: Wed, 27 Jan 2021 12:27:47 GMT
Referrer-Policy: strict-origin-when-cross-origin
X-Content-Type-Options: nosniff
Cache-Control: no-cache, must-revalidate, max-age=0, no-store
X-Frame-Options: SAMEORIGIN
Content-Type: text/html
Access-Control-Allow-Credentials: true
Pragma: no-cache
Set-Cookie: some-cookies
Expires: Wed, 11 Jan 1984 05:00:00 GMT
Access-Control-Allow-Origin: https://www.example.com.com
cf-edge-cache: cache,platform=wordpress
expect-ct: max-age=604800, report-uri="https://report-uri.cloudflare.com/cdn-cgi/beacon/expect-ct"
nel: {"max_age":604800,"report_to":"cf-nel"}
report-to: {"group":"cf-nel","endpoints":[{"url":"https:\/\/a.nel.cloudflare.com\/report?s=some-token"}],"max_age":604800}
cf-cache-status: DYNAMIC
cf-request-id: 07e569767900001c377fb67000000001
cf-ray: 618278372fc81c37-SOF
x-robots-tag: noindex
Server: cloudflare
Request Data
MIME Type: application/x-www-form-urlencoded
action: my_ajax_callback
term_id: 1209
page_id
And this is the from the access.log:
xx.xxx.xx.xxx - - [24/Mar/2021:10:16:46 +0000] "POST /wp-admin/admin-ajax.php HTTP/1.0" 200 12203 "https://example.com/some-page/" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/14.0.3 Safari/605.1.15"
UPDATE
I have to say that this is happening only on Safari and no other browser. Also I'm running Safari in VM with Mojave, not sure if this is related, but I though it is worthy to mention this.
I have tried to pause the CF service, and this change was visible on all other browsers but Safari continued to server the site over CF (I can see in the response header server that its value was cloudflare while on the other browsers it was nginx). I've flushed the DNS in the terminal and restarted VM a few times but this didn't changed.
I have also disabled all the security and firewall features on CloudFlare after I enabled it again but this also didn't solve the problem. I'm starting to believe that the problem lies some where in Safari and not in CF.
Try turning Cloudflare off, the setting is called "Pause Cloudflare on Site" to isolate it and see if that makes a difference. Maybe you have some goofy modsec rules in place?

Status 200 (from disk cache) and 304 Not Modified issue

I'm using Next.js custom server, which by default sends strong ETag header on each page GET request. For each request I also manually add Cache-Control header res.setHeader('Cache-Control', 'public, max-age=${60 * 60}, s-maxage=${60 * 60 * 24}, must-revalidate')
Also I'm using Cloudflare's loadbalancing and caching mechanism. According to this documentation https://support.cloudflare.com/hc/en-us/articles/218505467-Using-ETag-Headers-with-Cloudflare I sutisfied each requirement related to strong ETag. And the page rule was configured as following:
page rule configuration screenshot.
First strange behaviour is that on a client in headers I noticed for some reason weak ETag. Also the behaviour of caching is little strange. If I'll open a new site post, I'll be usually faced with cf-cache-status: HIT header, which means that Cloudflare already have prepared cache for this specific post. My expectation is that after page reloading in same tab, the page will be recreated form disk cache, but for some reason it makes a request, result of which is status 304 (Not Modified). BUT, if I'll copy the url and open the same post in new tab, it will be recreated from disk cache (as it should), and also after page reloading it makes request with response 304 (Not Modified).
Direct origin server request-response:
General:
Request URL: ...
Request Method: GET
Status Code: 200 OK
Remote Address: ...
Referrer Policy: strict-origin-when-cross-origin
Response headers:
cache-control: public, max-age=3600, s-maxage=86400, must-revalidate
connection: keep-alive
content-encoding: gzip
content-type: text/html; charset=utf-8
date: Thu, 28 Jan 2021 13:02:42 GMT
etag: "62e33-f1yLCVYVUzVH67UMp/2WOxQqfC8"
transfer-encoding: chunked
vary: Accept-Encoding
x-powered-by: Next.js
Request headers:
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9
Accept-Encoding: gzip, deflate, br
Accept-Language: ru-RU,ru;q=0.9,en-US;q=0.8,en;q=0.7,uk;q=0.6
Cache-Control: no-cache
Connection: keep-alive
Cookie: _ga=GA1.1.1009400285.1608315387; _gid=GA1.1.1795438935.1611755271; _gat=1
Host: ip_here
Pragma: no-cache
Sec-Fetch-Dest: document
Sec-Fetch-Mode: navigate
Sec-Fetch-Site: same-origin
Sec-Fetch-User: ?1
Upgrade-Insecure-Requests: 1
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.104 Safari/537.36
Cloudflare proxy request-response:
General:
Request URL: ...
Request Method: GET
Status Code: 200
Remote Address: ...
Referrer Policy: strict-origin-when-cross-origin
Response headers:
age: 44448
cache-control: public, max-age=3600, s-maxage=86400, must-revalidate
cf-cache-status: HIT
cf-ray: 618ac665c984351f-KBP
cf-request-id: 07ea9a539d0000351f0faf7000000001
content-encoding: br
content-type: text/html; charset=utf-8
date: Thu, 28 Jan 2021 12:39:13 GMT
etag: W/"62e33-vLyavPBB7axQJnhj/OKdPyUNp+A"
expect-ct: max-age=604800, report-uri="https://report-uri.cloudflare.com/cdn-cgi/beacon/expect-ct"
nel: {"max_age":604800,"report_to":"cf-nel"}
report-to: {"endpoints":[{"url":"https:\/\/a.nel.cloudflare.com\/report?s=4ASHxxkyb8necnQhGaz8th4W%2FcFEwzrBwYiidFGsHK5ZZJ%2BGEYWbmOlDSC2Uep2TYw8vYUm0DL4WkrdC9xsIK%2F6j0G1QF%2BK5817fQQ%3D%3D"}],"max_age":604800,"group":"cf-nel"}
server: cloudflare
vary: Accept-Encoding
x-powered-by: Next.js
Request headers:
:authority: ...
:method: GET
:path: ...
:scheme: https
accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9
accept-encoding: gzip, deflate, br
accept-language: ru-RU,ru;q=0.9,en-US;q=0.8,en;q=0.7,uk;q=0.6
cache-control: max-age=0
cookie: _ga=GA1.2.33365049.1592837735; __cfduid=d58947d60ae6adfce59e944d190e702ae1610627770; _gid=GA1.2.788163791.1611406644; connect.sid=s%3AfLFtBQSejs6Jf0gkdqiRhyzAnu8ImE_J.KukkQj15FMXkfcW6alO6BPUYT8SgPWRqtu2xo2QRe8U; __cflb=0H28urhoa5eNWhDb7XVCL24Hq5fwW5bc37oc693mgWx; _gat=1
sec-fetch-dest: document
sec-fetch-mode: navigate
sec-fetch-site: same-origin
sec-fetch-user: ?1
upgrade-insecure-requests: 1
user-agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.104 Safari/537.36
Why is it happening? In ideal I want to recreate page from disk cache in nearest hour and after it make a revalidation request. And make Cloudflare's cache revalidation each day from origin server.
You can see in headers that ETag is different between origin server and cloudflare

JHipster: CORS fails on form login (actual request, not pre-flight)

I would like to extend my monolithic setup of jHipster with a second front-end application which accesses the same API from a different URL. As a first step, I've enabled CORS in the application.yml and I'm sending the request from the front-end with the withCredentials flag. I'm using sessions and no JWT authentication.
Many methods work now as expected, but not all. The pre-flight (OPTIONS request) always goes through and works as expected. The response of this call contains the correct CORS headers.
The actual request (e.g. the POST request to sign in), however, requires also a header (Access-Control-Allow-Origin) in the response. This header is automatically set on my custom REST interfaces, but it is not set on jHipster-generated methods like /api/authentication or /api/logout. It does also not work on Spring-Security-protected resources like /api/account (only if not logged in, 401, afterwards it works as expected with the correct headers)
As for the logout, for example, Google Chrome reacts with the following message in the console, even though the call goes through in the Network tab (POST response status 200):
XMLHttpRequest cannot load http://localhost:8080/api/logout. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:9000' is therefore not allowed access.
I was wondering, what I'm doing wrong here. I guess the headers are not properly set. I could now manually add the header (e.g. in the AjaxAuthenticationSuccessHandler), but that does not seem right.
I'm using the rather outdated version of jHipster 3.7.0. I would, however, prefer not to update the core project.
Do you have any idea, what could be causing this issue?
Headers
Here are the complete headers of the POST call to /api/logout. The OPTIONS call works as expected but in the POST response the Access-Control-Allow-Origin header is missing:
OPTIONS Request
OPTIONS /api/logout HTTP/1.1
Host: localhost:8080
Connection: keep-alive
Pragma: no-cache
Cache-Control: no-cache
Access-Control-Request-Method: POST
Origin: http://localhost:9000
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.113 Safari/537.36
Access-Control-Request-Headers: x-csrf-token
Accept: */*
DNT: 1
Referer: http://localhost:9000/
Accept-Encoding: gzip, deflate, br
Accept-Language: de-DE,de;q=0.8,en-US;q=0.6,en;q=0.4,de-CH;q=0.2,it;q=0.2
OPTIONS Response
HTTP/1.1 200 OK
Access-Control-Allow-Headers: x-csrf-token
Date: Mon, 11 Sep 2017 13:54:57 GMT
Connection: keep-alive
Access-Control-Allow-Origin: http://localhost:9000
Vary: Origin
Access-Control-Allow-Credentials: true
Content-Length: 0
Access-Control-Allow-Methods: GET,PUT,POST,DELETE,OPTIONS
Access-Control-Max-Age: 1800
POST Request
POST /api/logout HTTP/1.1
Host: localhost:8080
Connection: keep-alive
Content-Length: 0
Pragma: no-cache
Cache-Control: no-cache
Accept: application/json, text/plain, */*
Origin: http://localhost:9000
X-CSRF-TOKEN: [***token removed in this snippet***]
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.113 Safari/537.36
DNT: 1
Referer: http://localhost:9000/
Accept-Encoding: gzip, deflate, br
Accept-Language: de-DE,de;q=0.8,en-US;q=0.6,en;q=0.4,de-CH;q=0.2,it;q=0.2
Cookie: [***removed cookies in this snippet***]
POST Response
HTTP/1.1 200 OK
Expires: 0
Cache-Control: no-cache, no-store, max-age=0, must-revalidate
Set-Cookie: CSRF-TOKEN=null; path=/; Max-Age=0; Expires=Thu, 01-Jan-1970 00:00:00 GMT
Set-Cookie: JSESSIONID=[***removed jsessionID in this snippet***]; path=/; Max-Age=0; Expires=Thu, 01-Jan-1970 00:00:00 GMT
Set-Cookie: remember-me=null; path=/; Max-Age=0; Expires=Thu, 01-Jan-1970 00:00:00 GMT
X-XSS-Protection: 1; mode=block
Pragma: no-cache
Date: Mon, 11 Sep 2017 13:54:57 GMT
Connection: keep-alive
X-Content-Type-Options: nosniff
Content-Length: 0
Reproduction
You can reproduce this behavior by using this demo project of jHipster in version 3.7.0. Then, enable the CORS settings (all of them) in src/main/resources/application.yml. After that, create a new user on localhost:8080 and activate it. Finally, try to authenticate with the following JS snippet from another port (e.g. a simple node server or xampp). You can also try to make a simple POST call to /api/account, which will lead to a 401 error. See the Google Chrome console for the error message.
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.16.2/axios.js"></script>
<script type="text/javascript">
var Http = axios.create({
baseURL: 'http://localhost:8080/api',
});
Http.interceptors.request.use(function (config) {
config.xsrfCookieName = 'CSRF-TOKEN';
config.xsrfHeaderName = 'X-CSRF-TOKEN';
config.withCredentials = true;
return config;
});
var credentials = {
username: 'test-user',
password: 'test123',
rememberMe: true
};
Http.post('authentication', 'j_username=' + credentials.username +
'&j_password=' + credentials.password +
'&remember-me=' + credentials.rememberMe +
'&submit=Login');
</script>
It looks like you are running into this CORS issue where one of the filters before the CorsFilter in Spring Security's filter chain throws an error. The request never reaches the CorsFilter, causing the CORS headers to be missing in the response. That's why Chrome complains about the missing headers in the console even though it's a different error.
You need to put the CorsFilter before CsrfFilter and UsernamePasswordAuthenticationFilter so that if there's an issue with either of those filters, the response still gets the CORS headers. To accomplish this, add the following code to SecurityConfiguration.java:
// import CorsFilter
import org.springframework.web.filter.CorsFilter;
...
...
// inject for JHipster v3 apps, add to constructor for JHipster v4 apps
#Inject
private CorsFilter corsFilter;
...
...
// add this line in the configure method before ".exceptionHandling()"
.addFilterBefore(corsFilter, CsrfFilter.class)
Also in SecurityConfiguration.java, you can set #EnableWebSecurity(debug = true) to see the filter chain for each request. You can verify everything is correct by making sure the CorsFilter is before the CsrfFilter and UsernamePasswordAuthenticationFilter in the chain:
Security filter chain: [
WebAsyncManagerIntegrationFilter
SecurityContextPersistenceFilter
HeaderWriterFilter
CorsFilter <--------- Before CsrfFilter and UsernamePasswordAuthenticationFilter
CsrfFilter
CsrfCookieGeneratorFilter
LogoutFilter
UsernamePasswordAuthenticationFilter
RequestCacheAwareFilter
SecurityContextHolderAwareRequestFilter
RememberMeAuthenticationFilter
AnonymousAuthenticationFilter
SessionManagementFilter
ExceptionTranslationFilter
FilterSecurityInterceptor
]
If you are running into CSRF issues in your new client, you may need to make a GET request after a POST to refresh the CSRF token. An example of how JHipster handles this can be seen when logging out.
Have a look at how the org.springframework.web.cors.CorsConfiguration Spring bean is configured in the JHipster common application properties. I think you are missing the following configuration line:
exposed-headers: "Authorization"
I just documented this a few hours ago, and also added this configuration by default a few hours ago.
In the next release, which should be out tomorrow, you should have a new page called Separating the front-end and the API server that should explain that better - and if you have found a better solution, don't hesitate to improve that page, it's a first version.

Can't get Access-Control-Allow-Origin header to work as I expected

There are a lot of questions on this subject, but I still can't seem to resolve my issue.
I have a game that I'm trying to get working with HTML 5 in Chrome. Link here.
The game is written using libgdx and I'm posting json data from my app engine hosted back end. I've done quite a bit of reading and I think I understand the issue with cross domain access, I also think I understand how to resolve it but can't.
The full error is
XMLHttpRequest cannot load http://1-1-51.wordbuzzweb.appspot.com/Login. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://wordbuzzhtml5.appspot.com' is therefore not allowed access.
As you can see, this says No 'Access-Control-Allow-Origin' header is present on the requested resource.. But if I look at the headers for the requested resource, they are as follows.
Date: Thu, 18 Jun 2015 21:59:34 GMT
Content-Encoding: gzip
Server: Google Frontend
Vary: Accept-Encoding
Access-Control-Allow-Methods: GET, POST
Content-Type: application/json
Access-Control-Allow-Origin: *
Alternate-Protocol: 80:quic,p=0
Cache-Control: private
Access-Control-Allow-Headers: Content-Type
Content-Length: 127
As you can see, there is an Access-Control-Allow-Origin header included.
If someone could please tell me what I'm doing wrong, that'd be appreciated.
The request header is as follows using the POST method.
Host: 192.168.254.1:8081
Pragma: no-cache
Cache-Control: no-cache
Origin: http://localhost:8080/
User-Agent: Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/44.0.2403.52 Safari/537.36
Accept: */*
Referer: http://localhost:8080/html/
Accept-Language: en-GB,en;q=0.8
Content-Length: 25
Content-Type: application/json
Since you are getting some headers back in the response, that's a good indication that the request IS reaching the server, however, the fact that it isn't hitting your server route points to the problem being the request being made doesn't match any of your routes. The request is likely an OPTIONS request rather than a POST request, which commonly happens when you make a CORS request from the browser that isn't a "simple request".
The solution would be to either make it a "simple request", or to have your server respond to OPTIONS requests. It's far easier to just make your server respond to OPTIONS requests, because sometimes even "simple requests" still send OPTIONS requests.

Firefox CORS Cross Domain Resource Sharing Pre-Flight Debugging

I'm trying to get Firefox to allow me to make an XmlHttpRequest for data from an application port.
I can see that the initial send triggers an OPTIONS message, and I have trapped this using NetMon, and I can see the HTTP fields...
OPTIONS /any.htm HTTP/1.1
Host: www.mysite.co.uk:10090
User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64; rv:18.0) Gecko/20100101 Firefox/18.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-gb,en;q=0.5
Accept-Encoding: gzip, deflate
DNT: 1
Origin: http://www.mysite.co.uk
Access-Control-Request-Method: POST
Access-Control-Request-Headers: content-type
Connection: keep-alive
Pragma: no-cache
Cache-Control: no-cache
I respond to this with an OK to tell FireFox to get a move on and send me the data in the XHR request...
HTTP/1.1 200 OK
Access-Control-Allow-Methods: POST,-GET,-OPTIONS
Access-Control-Allow-Origin: *
Access-Control-Max-Age: 172800000
Server: Kawasu-OrderSub
Date: Wed, 23 Jan 2013 15:00:50 GMT
But the POST is never sent, which I assume means that FireFox is not happy with the 200 OK response. The POST sends data with a Content-Type of "application/json"
I've got FireBug and the Net tab has the XHR button, but this will only show the XHR after the pre-flight check has been passed.
Main Question: How can I see (and debug) what FireFox does not like about the server response?
Much obliged for any help in advance.
You need to include the Access-Control-Allow-Headers: content-type response header. This is because the request has the Access-Control-Request-Headers: content-type header, and this value needs to be included in the response.

Resources