I am working on two projects namely administrator and authentication.
The administrator project is hosted locally on port 3002 and the authentication project is hosted locally on port 3005.
I did set up of swagger on administrator using libraries swagger-ui-express
and yamljs
.
The code for setting up swagger in app.js
is as below -
const swaggerUi = require('swagger-ui-express');
const YAML = require('yamljs');
const swaggerDocument = YAML.load('./swagger.yml');
const swaggerOptions = {
explorer: true,
validatorUrl: null,
customCss: '.swagger-ui .topbar { display: none }',
// customCssUrl: '/custom.css'
// customJs: '/custom.js'
};
app.use(
'/api-docs',
function (req, res, next) {
swaggerDocument.host = req.get('host');
req.swaggerDoc = swaggerDocument;
next();
},
swaggerUi.serve,
swaggerUi.setup(null, swaggerOptions)
);
I am able to call the APIs of the Administrator project since the setup of the swagger is in the same project (same server and same port). I have selected the appropriate server(localhost) and port(3005) for the authentication project from the list of server dropdowns. However, when I am trying to call the APIs of the Authentication project from the authentication project, I am getting a CORS error.
I read the documentation swagger documentation for the CORS error. As per the documentation, I added the relevant CORS headers while calling an API and did CORS set up in the backend for the express server as well.
A relevant related question in Java.
CodePudding user response:
Since the message appears in the console(see comments):
Refused to connect to 'localhost:3005/auth/login' because it violates the following Content Security Policy directive: "default-src 'self'". Note that 'connect-src' was not explicitly set, so 'default-src' is used as a fallback.
this means that CSP is interfering and blocks connects. The fact is that 'self'
covers standart ports only (80 for http:/ws: and 443 if https:/wss:).
Therefore you have to change default-src 'self'"
to the default-src 'self' localhost:3005
(with exact port number) in the Content Security Policy. Since connect-src
is omitted, it fallback to the default-src
.
May be better to use default-src 'self' localhost:*
rule (*
means any port number). Browsers treat localhost
as safe source (you own device) so is secure enough to allow any ports on localhost
.
In this case, fallback directives (img-src
, script-src
, style-src
, frame-src
, etc) will not block any sources downloaded from localhost on any port, what can be convenient in development mode.
Note 1: however, if you need to prepare CSP for the production mode, you can place blocked sources in the relevant directives. In this case CSP will be default-src 'self'; connect-src localhost:*;
because blocking is observed in the connect-src
.
Note 2: Quite possible CSP header default-src 'self'
is set by Helmet middleware the latest version of which self-publishes CSP with a default rules.