Forbit CORS request in node.js - node.js

I have a nodejs Express app which serves a static front-end app. I have an endpoint that I'd like to prevent the access from all the others domains.
One solution could be using CRSF but I'd prefer avoiding this. Is there a simple way?
My app is very simple:
app.use(express.static(path.join(__dirname, '/dist')));
app.use(bodyParser.json());
app.post('/endpoint', (req, res) => {
res.send();
});
app.listen(process.env.PORT || 8080);

Does the domain have a static IP? You could add your domains IP to a whitelist blocking access to your endpoint from all IP's bar your own:
express-ipfilter
If you don't have a static IP so that you can block requests you could start by configuring CORS with the Access-Control-Allow-Origin header set to your domain. This will block cross origin access from the browser but isn't a complete fix for what you want.
Configuring CORS

Related

CORS error using passport-azure-ad on React + Express app

I have a React + Express app for which I am using the passport-azure-ad OIDCStrategy, but I'm having trouble with CORS.
The error I am receiving is:
Access to XMLHttpRequest at 'https://login.microsoftonline.com/...' (redirected from '{SERVER_URL}') from origin '{FRONTEND_URL}' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
My frontend and backend are on different domains (I added a header on the backend to allow the frontend origin).
I tried adding both urls as Redirect URIs, but that doesn't seem to help.
Is there a way to set Access-Control-Allow-Origin headers in Azure? Or is there a configuration in the React code which I'm missing?
Is there a way to set Access-Control-Allow-Origin headers in Azure?
Or is there a configuration in the React code which I'm missing?
Generally, this error occurs when the front end and backend is running on different ports.
The browser will not accept the responses from the backend because of the CORS headers not present.
So, we have to add the CORS headers in the backend request to overcome this issue by using the cors npm package below:
var express = require('express')
var cors = require('cors')
var app = express()
app.use(cors())
It enables CORS headers with all the requests.
you can refer to cors documentation for more information.
Also, We can enable CORS for Azure App Service in azure portal as mentioned here.
You have to use CORS package in the backend and give CORS access in your domain like
const cors = require('cors')
var corsOptions = {
origin: '*',
optionsSuccessStatus: 200 // some legacy browsers (IE11, various SmartTVs) choke on 204
}
app.use(cors(corsOptions));
I want to assume you already set up CORS options in your backend. So, from the error one could see that the frontend is able to access the backend but not able to get access to the 3 party 0auth from Microsoft azure right.
I am sure if you ran both the frontend and backend on the same port it would be successful provided you already set up your azure account to receive requests from your backend end point.
The problem is you running it on different ports, your react app on a particular port and the backend on another port. Then you used fetch in the react app to try and get the backend which will then send requests using the passport-azure to Microsoft.
So instead of using fetch from react to backend to 0auth service, use an anchor tag.
Kindly check out this github issue as this person also encountered this same error
"Fixed. Don't use fetch from react to api to oauth service. Use a link (anchor/location.href) instead and let the flow of the oauth process take over in the browser." - what the issue owner said.
I hope it helps.

Express: does cors configuration depend on server TTL?

I've successfully deployed my Express API app to AWS elastic beanstalk. I have a React front end that is hosted on S3.
Both are on the same domain with the front end being at example.com & the API at api.example.com
Both have certificates and are secured.
const express = require('express');
const cors = require('cors')({
Origin: 'https://example.com'
});
// followed by required middleware
app.use(cors());
//followed by app constants
app.use((e, req, res, next) => {
res.header("Access-Control-Allow-Origin", "https://example.com");
res.header('Access-Control-Allow-Methods', 'DELETE, PUT, GET, POST');
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
if (e) {
console.log(e);
res.status(500).send(e.message);
}
next();
})
// followed by app routes
When I try and register a user on my site, I get the error:
Access to XMLHttpRequest at 'https://api.example.com/users/signup/' from origin 'https://example.com' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
This topic has of course been covered multiple times on Stack Overflow (which I've gone through multiple solutions this morning), but my question has to do with the actual server where the API is being hosted.
In the hosted zone for api.example.com, it has a TTL of 172800(48 hours). Does this mean that my changes won't be reflected in that time? If that is the case, does this mean that every time you deploy code it resets the TTL?
I'm a front end dev working on a side project, so this really isn't my area of expertise. Any DevOps or BackEnd Devs have any ideas? Thanks in advance!
In the hosted zone for api.example.com, it has a TTL of 172800(48 hours). Does this mean that my changes won't be reflected in that time? If that is the case, does this mean that every time you deploy code it resets the TTL?
No.
The TTL is how long other DNS servers are expected to cache the DNS information (e.g. which server the domain name points to).
It has nothing to do with deployment of code.
Your problem is unrelated to that. I'd add some logging to the server-side code to see which routes and middleware were actually hit as well as monitoring the precise request and response you are getting in the Network tab of your browser.
There a preflight OPTIONS request can be made by the browser for the particular types of cross-domain requests. If the response on that request is not successful or doesn't have CORS headers you will also get such error.
So I suppose that you should add a route in your Express app to handle preflight requests and send back the same CORS headers or just use express-cors-middleware.

How do I prevent the "appspot.com" of my App Engine app?

I have a custom domain added that I added to App Engine. For example, let's say my custom domain is "example.com".
My app is served with Node.js, and I when I deploy my app through App Engine, it gives me this address to access to it:
"example.appspot.com".
How do I prevent this? I want to serve my app only on "example.com".
SOLVED: I'm using this middleware to prevent those hostnames and it works, at least for what I kind of wanted:
var redirect = function(req, res, next) {
if (req.hostname.search('appspot') !== -1) {
res.redirect(301, 'https://www.example.com');
next();
}
next();
};
app.use(redirect);

How to Restrict the anonymous domain accessing my webisite

! I have implemented a WebApp and SQL-DB.
added custom domain and SSL certificates (which bought at CA).
for SSL offloading purpose we configured an azure application gateway.
with all setup.
next, we configured azure traffic manager so that traffic manager decide active web app routing.
our concern is when I adding the CNAME record for traffic manager in GoDaddy it is routing to WebApp, everything is great.
but when I search "xxxx.com" Digwebinterface it shows all connections to WebApp
in this, I took the traffic manager CNAME record and added to another domain then the duplicate domain also accessing all my content of the website and even create a record in SQL also.
in this scenario I losing my website restriction unauthorized domain can map site
any suggestion and insights it would be grateful to
thank you
The simple way is to create a filter in your code for inspecting the host of headers of request to allow or deny the accessing from different domain.
Here is my sample code in Node.js with express.
const express = require('express')
const app = express()
const port = 3000
const allowedHosts = [`localhost:${port}`]
var domainFilter = function(req, res, next) {
if(allowedHosts.includes(req.headers.host)) {
next()
} else {
res.status(403).end()
}
}
app.use(domainFilter)
app.get('/', (req, res) => res.send('Hello World!'))
app.listen(port, () => console.log(`Example app listening on port ${port}!`))
It will allow the request from localhost:3000 and deny the request from 127.0.0.1:3000 or others, as the figures below.
Fig 1. Allow the request from localhost:3000
Fig 2. Deny from 127.0.0.1:3000 or others
Hope it helps.

SSL certificate propagation issue with custom domain on Bluemix app

I uploaded my SSL certificate in the section of my custom domain in the space of my organization. I linked the domain with my application and I have created the CNAME record in my DNS to my broken app xxxxx-gb.bluemix.net .eu.
When I try to reach my application through my domain custom, I served me the Bluemix certificate and not mine.
I tried to add a proxy on my server (NodeJS) but the situation does not change.
app.enable('trust proxy');
app.use(function (req, res, next) {
if (req.secure) {
// request was via https, so do no special handling
next();
} else {
// request was via http, so redirect to https
res.redirect('https://' + req.headers.host + req.url);
}
});
How can I fix the problem ? I need my certificate, to call my API, from my mobile application, it is the certificate must necessarily be mine and then TRUSTED
You need to map the CNAME to the secure endpoint for the Bluemix region you are using, in your case it should be secure.eu-gb.bluemix.net.
When receiving the request from your custom domain Bluemix will map it internally to your app.
More details in the documentation link below:
https://new-console.ng.bluemix.net/docs/manageapps/updapps.html#domain

Resources