GET request throws error after app implemented SSL: Mixed Content: This request has been blocked; the content must be served over HTTPS" - angularjs

Mixed Content: The page at 'https://www.example.com/dashboard' was
loaded over HTTPS, but requested an insecure XMLHttpRequest endpoint
'http://api.example.com/inventory/10/'. This request has been blocked;
the content must be served over HTTPS.
We have this Angular web app that runs with Flask on the back-end.
Everything was working fine until we implemented SSL. Afterwards, we keep getting this strange error everywhere.
Now, the $http.get request in my dashboard.js is definitely calling "https://api.example.com/inventory/10" in the code below and yet the error is claiming that we are trying to request "http" instead.
$http.get($rootScope.baseUrl+'/inventory/' + item.id)
where rootScope.baseUrl is "https://api.example.com".
It's really weird because some GET requests ARE going through from our web application to our back-end, but some requests are throwing this weird error.
Here's the header that gets an error in our Network tab of the console in chrome.
Request URL:https://api.example.com/inventory/10 Request Headers
Provisional headers are shown Accept:application/json, text/plain, /
Origin:https://www.example.com
Referer:https://www.example.com/dashboard

It was a weird case that came down to removing a forward slash from the end of a URL fixing everything. Somehow, whenever we made a GET request using $http in Angular like baseurl + inventory.id + "/", it would make a http request but as soon as remove that slash, it would make the https request correctly.
Still so confused

I think the root of the problem is in server redirects. I was able to resolve same issue with SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https') setting for Django (its running behind AWS balancer). Here is documentation.

Related

Access-Control-Allow-Origin Error Only on a Single Route, Only When Deployed to GAE

I'm using google app engine to host both my frontend and my api backend. I'm getting the following errors when I'm polling the "slicingdone" route on my backend:
bootstrap e65cef5bb029055e1719:2 GET
https://playloopsbackend-217106.appspot.com/playloops/slicingdone 502
send # bootstrap e65cef5bb029055e1719:2
/videotogifs:1 Access to XMLHttpRequest at
'https://playloopsbackend-217106.appspot.com/playloops/slicingdone'
from origin 'https://playloopsfrontend.appspot.com' has been blocked
by CORS policy: No 'Access-Control-Allow-Origin' header is present on
the requested resource.
I poll the slicingdone function to figure out when trimming of a video on my backend is finished. It works locally but is presenting the above errors when deployed to gcloud.
slicingdone function on my backend looks like this(Express):
slicingdone(req, res, next) {
if(slicingIsDone == true){
res.status(200).send('true');
slicingIsDone = false;
}else{
res.status(200).send('false');
}
}
*Every other route on my backend works fine even when deployed. I have similar functions on the backend that manipulate videos using ffmpeg in different ways. I have whitelisted my frontend url on my backend, so I'm not sure why I'm getting these CORs errors. I store the video results in google cloud storage--perhaps I need to add my backend url to google cloud CORS whitelist?
Any help is much appreciated! Thank you!

Access control allow origin with ReactJS sample web app

I am facing problem with the following CORS issue when I run my ReactJS sample web app in Chrome browser.
Access to XMLHttpRequest at 'https://XXXX.XXX/YYY/ZZZ/' from origin 'http://localhost:3003' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status.
I read the solution and installed CORS Chrome plugin. I added REST URL in CORS settings as shown in below screenshot. I cleared Chrome browser history and try running ReactJS web app, but still it is throwing the same error. Can someone guide how to exactly fix this? I also tried
'Access-Control-Allow-Headers': '*',
'Access-Control-Allow-Origin': '*',
in code, but not fixed this issue.
You can try a workaround with https://cors-anywhere.herokuapp.com
Have a look at my solution in here: https://stackoverflow.com/a/52986448/5692089

CORS request did not succeed - react

I make this API request , using axios in ReactJS
axios.post(`${API_URL}/valida_proximo`, {
id: images.map(image => image.id)
},
getAxiosConfig())
// this.setState({ images, loadingAtribuiImagens: false})
}
It works really well in Google Chrome, but on Firefox I receive an error:
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost:5000/valida_proximo. (Reason: CORS request did not succeed).[Learn More]
What can I do?
This is my API
#blueprint.route('', methods=['POST', ])
#jwt_required()
def index():
if request.json:
id_usuarioImagem = request.json.get('id')
imagens_selecionadas =
UsuarioImagem.query.filter(UsuarioImagem.id.in_(id_usuarioImagem)).all()
if imagens_selecionadas:
for imagem_selecionada in imagens_selecionadas:
imagem_selecionada.batido=True
db.session.commit()
return 'ok', 200
return 'error', 400
CORS errors are usually associated with cross domain requests and something not configured to accept a request on the recipient side of the request. The fact that chrome is working but firefox doesn't seems rather strange.
This was a method I used:
Open Firefox browser and load the page.
Perform the operation which is throwing Cross Origin Request Security (CORS) error.
Open firebug and copy the URL which is throwing Cross Origin Request Security (CORS) error.
Load the same URL in another tab in same Firefox browser.
Once you open the URL in another tab will ask you to add the certificate.
After adding the certificate will resolve Cross Origin Request Security (CORS) error and now you will not be getting this error.
I'm not too familiar with Axios, but it looks like you're making a post request from your React to your Flask backend. If the front-end and the backend are on different ports (like your Flask seems to be on PORT 5000), then you're making a CORS request.
With CORS, depending on what you're posting, you might need to include some Access-Control headers in your Flask response object. You can do this either manually, or just pip-installing and using the 'flask-cors' package. Import the package into your app factory and use it like so (see their docuementation for more info):
from flask_cors import CORS
def create_app(test_config=None):
app = Flask(__name__, instance_relative_config=True)
CORS(app)
The request might also get 'preflighted' with an 'OPTIONS' request, also depending on the nature of your POST. More information would be helpful
This is a bug in firefox.
if you follow the link (MDN) in the error msg . you will find:
What went wrong?
The HTTP request which makes use of CORS failed because the HTTP connection failed at either the network or protocol level. The error is not directly related to CORS, but is a fundamental network error of some kind.
which i read as the connection failed and not a problem with CORS settings.
you will just have to ignore the error message until firefox gets it fixed.
The error has something to do with refreshing the page and long polling requests or service workers and polling requests.
If anyone sees this question again, I had this problem because I made a request to https://url instead of http://url

request has been blocked; the content must be served over HTTPS

I'm doing application with spring security and Spring MVC in back end and Angular in front end.
My problem is that I do the logged in correctly, but the problem in logged out I implemented correctly in my localhost: http://localhost:8080 worked without problem. When I change it to https:// I get this error:
Mixed Content: The page at '' was loaded over HTTPS, but requested an insecure XMLHttpRequest endpoint ''. This request has been blocked; the content must be served over HTTPS.
I want to know how to correct that? And how to know which url blocked by https in the browser for example chrome?
This post which gives a solution to your problem: http://www.learningthegoodstuff.com/2015/08/mixed-http-error-with-spring-security.html
All the details are explained there, basically all you have to do is add this two lines to my application.properties file:
server.tomcat.remote_ip_header=x-forwarded-for
server.tomcat.protocol_header=x-forwarded-proto
I fixed by removing a forward slash from the end of a URL fixing everything.this is help me : GET request throws error after app implemented SSL: Mixed Content: This request has been blocked; the content must be served over HTTPS"
This happens when the server is using http (non secured). You can fix it by enforcing https for all resources in the backend. Check here for more details.
In #Jabir Minjibir's answer there is very good link to describe the error. As sum up, when your application works with httpS scheme you can't make visits to unsecure links which is http.
I got this error and fixed it like I wrote below:
Mixed Content: The page at 'https://stackblitz.com/' was loaded over HTTPS, but
requested an insecure XMLHttpRequest endpoint 'http://172.19.0.62:920/'.
This request has been blocked; the content must be served over HTTPS.
You can mask unsecure links with simple-https-proxy npm package. In my experience I was coding an angular sample on httpS://stackblitz.com and I was trying to connect to an Elasticsearch server which doesn't have a domain name. I needed to make it working with ssl but I couldn't modify it's scheme. Thus I installed a proxy which can work secure (httpS).
I installed the npm package:
npm i -g simple-https-proxy#latest
Then I created certificate:
simple-https-proxy --makeCerts=true
Then I ran it
simple-https-proxy --target=http://172.19.0.62:9200 --port=9201 --rewriteBodyUrls=false
In another example:

Getting CORS error in angularJS front end

I am using a flask server with an angular front end. Up until recently, I was running the project on my local and had no issues.
I now moved my project to a remote server and have been getting the following error. I am not sure what i'm doing wrong:
My error:
XMLHttpRequest cannot load http://ec2-..../api/loginStatus/. No
'Access-Control-Allow-Origin' header is present on the requested
resource. Origin 'http://localhost:8100' is therefore not allowed
access. The response had HTTP status code 503.
The snippets of my flask server side code (where I am adding my headers to the response is given below):
#app.after_request
def after_request(response):
response.headers.add('Access-Control-Allow-Origin','http://localhost:8100')
response.headers.add('Access-Control-Allow-Headers', 'Content-Type,Authorization')
response.headers.add('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE')
response.headers.add('Access-Control-Allow-Credentials', 'true')
return response
I use both restangular and $http methods in my front end angularjs.
I have added the following lines in the .config of my main module:
.config(['RestangularProvider', '$stateProvider', '$urlRouterProvider','$httpProvider',
function(RestangularProvider, $stateProvider, $urlRouterProvider,$httpProvider) {
//$httpProvider.defaults.useXDomain = true;
$httpProvider.defaults.headers.common['Access-Control-Allow-Origin'] = "http://localhost:8100";
$httpProvider.defaults.withCredentials = true;
$httpProvider.defaults.headers.common = 'Content-Type: application/json';
delete $httpProvider.defaults.headers.common['X-Requested-With'];
Would someone be able to help me out here? I've referred to a lot of material and I am not sure what i'm doing wrong.
PS: I am getting 200 status messages on my server. I am therefore assuming that the error is in my front end and not my server side. Please correct me if I am wrong
Regards,
Sunil
EDIT
Hi everyone, I have solved the issue. I would like to thank #Mathijs Segers and #Hassan Mehmood for their inputs.
It turns out that there was a nginx configuration issue which led to the server becoming unavailable.
Firstly, there was an issue with the symbolic link that was being created for the flask backend (I am running my server side through a git repo on /home/username and then creating a symbolic link at /var/www/sitename.com
I was also throttling the number of requests that can be sent in a second (users could send only 1 every 2 seconds) resulting in the 503 error.
The original code I put up worked fine after I fixed it.
Eyooo, it is actually on your server side. You need to provide correct headers.
So you've tried this, I have no experience with flask but this I don't like;
response.headers.add('Access-Control-Allow-Origin','http://localhost:8100')
for testing purposes I suggest you just change the http:// part, to *
so
response.headers.add('Access-Control-Allow-Origin','*')
If that doesn't work verify that the header is actually being set, you could use a different program which doesn't care for CORS like postman or directly calling it in the browser if it doesn't depend on Accept headers.
here is some more readings about what it all is about.
https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS
EDIT:
Ok silly of me: The response had HTTP status code 503.
This part in the error actually states what kind of response your server is giving, so currently there is an error on your server side. This happens when it is f/e down or what not.
So it seems that you're not doing anything strange, but your server side seems broken.
XMLHttpRequest cannot load http://ec2-..../api/loginStatus/. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8100' is therefore not allowed access. The response had HTTP status code 503.
So this error here, I suggest looking at your headers, and maybe disable some. You currently allow only 2 request headers that might cause some issues as well?
Flask-CORS
A Flask extension for handling Cross Origin Resource Sharing (CORS), making cross-origin AJAX possible.
Installation
Install the extension with using pip, or easy_install.
$ pip install -U flask-cors
Simple Usage
In the simplest case, initialize the Flask-Cors extension with default arguments in order to allow CORS for all domains on all routes. Read More.
from flask import Flask
from flask_cors import CORS, cross_origin
app = Flask(__name__)
CORS(app)
#app.route("/")
def helloWorld():
return "Hello, cross-origin-world!"
Reference: https://flask-cors.readthedocs.io/en/latest/

Resources