How to set X-Frame-Options header in angularjs? - angularjs

I'm getting an OWASP ZAP Scanning alert:
Medium (Medium) X-Frame-Options Header Not Set
Description X-Frame-Options header is not included in the HTTP response to protect against 'ClickJacking' attacks.
URL https://10.11.12.13/web/network/config.html
Method GET
Parameter X-Frame-Options
To fix the alert I set HTTP headers in app.js
$httpProvider.defaults.headers.get['X-Frame-Options'] = 'DENY';
When building a project I get a TypeError
[INFO] TypeError: 'undefined' is not an object (evaluating '$httpProvider.defaults.headers.get['X-Frame-Options']='DENY'')
Am I doing something wrong? Or is there a different way of fixing the alert?

You didn't follow the syntax in the article you linked, which lists:
$httpProvider.defaults.headers.get = { 'My-Header' : 'value' }
So yours should be something like :
$httpProvider.defaults.headers.get = { 'X-Frame-Options' : 'DENY' }
As MrWook suggested that might not be the best option. You should also checkout these answers:
How do I set X-Frame-Options as response header in angularJS?
angular js load external site in iframe

$httpProvider.defaults is used to set request headers. Leaving aside your error in how you are trying to use it, X-Frame-Options is a response header.
You can't set response headers in Angular: It is a client-side application.
You need to configure your HTTP server (https://10.11.12.13) to include the header.
How you do that depends on which HTTP server software you use. This guide, for example, covers Apache HTTPD and Nginx. You'll need to find documentation for the software you are using.

Related

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

ExpressJS not sending Access-Control-Allow-Origin header

I am working on a project where I need an angular web app to be able to access a node/express based backend, and I am attempting to use Cors. However, the express server seemingly won't send the Access-Control-Allow-Origin header, and I have no clue why. I've tried creating a middleware as such:
this.app.use((request, response, next) => {
response.header("Access-Control-Allow-Origin", "*");
next();
}
I've also tried doing something similar individually for each request, using setHeader(), header(), set() and append(), but none of these work either. I'm currently using the cors npm package, but that also isn't working with the following code:
this.app.use(cors({
origin: "http://localhost/4200"
}));
this.app.options("*", cors({
origin: "http://localhost/4200"
})
);
I've checked that none of these are adding the relevant header to the response via postman. Express is adding the "error" header I use to give a human-readable description of the error, but not "Access-Control-Allow-Origin".
I'm writing this in TypeScript.
Did you restart your express server after making the change?
Did you try also adding the Access-Control-Allow-Headers header?
Did you check your middleware is invoked on request?
Did you check your middleware is registered before listen is called?
If both is guaranteed it must have a reason depending on a other part of your Application. So you should provide more information about booting and structure of files and directories.
Turns out the problem wasn't with the code, but with the compiler setup. I deleted and recreated the tsconfig.json file, and it works now.

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/

Call Django API running on a server from Angular running locally

I am learning with Django and Angular.
I have setup a Django API back-end on on http://serverip:8666/athletics/
I have created a small Angular application that I am running from my local machine.
The following code in my Angular app:
$scope.list_athletes = function(){
console.log('hey');
$http
.get('http://serverip:8666/athletics/')
.success(function (result) {
console.log('success');
})
}
generates the error:
XMLHttpRequest cannot load http://serverip:8666/athletics/. No
'Access-Control-Allow-Origin' header is present on the requested
resource. Origin 'http://127.0.0.1:65356' is therefore not allowed
access.
What causes this error? How can I resolve it so that I can access the Django API from my local Angular app?
The problem you're having is related to not having CORS enabled.
As a security policy, JavaScript can't make requests across domains while running in your browser. This is meant to prevent untrusted code from executing without the user's knowledge. The workaround is to enable CORS by white listing domains.
You need to set the Access-Control-Allow-Origin response header in your responses like so:
def my_view(request):
data = json.dumps({'foo':'bar'})
response = HttpResponse(data)
response['Access-Control-Allow-Origin'] = 'http://127.0.0.1:65356'
return response
This will enable CORS for your angular app. You can even add django-cors-headers to your project to have this functionality implemented for you. This can be added to any Django response object, such as django.http.repsonse.HttpResponse. Because you appear to be using a DRF Response object, you may need to use something like
return Response(serializer.data, headers={'Access-Control-Allow-Origin': 'http://127.0.0.1:65356'})
to set your response headers.
You should also check out this site for more information on how to enable CORS in your webapp.
Have you done the settings part in settings.py
INSTALLED_APPS = (
'corsheaders',
)
MIDDLEWARE_CLASSES = (
'corsheaders.middleware.CorsMiddleware',
)
CORS_ORIGIN_WHITELIST = (
'http://127.0.0.1:65356'
)
And also include CORS_ALLOW_CREDENTIALS, CORS_ALLOW_HEADERS settings

Sails.js modified header - cross domain

does anybody know where I can set a header in Sailsjs?
I have to set the Access-Control-Allow-Origin header that I can use my sails instance as API.
Currently I get this error if I try to send a request via $http.get in AngularJs
[Error] XMLHttpRequest cannot load http://acreasyURL.io/signin. Origin http://myhostOnMyMac.io:8000 is not allowed by Access-Control-Allow-Origin.
Any idea?
Cheers!!
Normally, you don't have to set it manually.
Sails has some CORS functionality built in:
https://github.com/balderdashy/sails-docs/blob/bc148104378f1ad590a69220c25f60fe41a59790/config.cors.md

Resources