0

I have an application on nodejs running on a kinghost.com host, it enabled SSL we will encrypt, but my application still does not respond with https only by http. I made this setting below in the application so that the requests were turned into https, but it did not work. Could someone tell me what to do, where I am wrong, some example. I do not know what else to do.

File app.js

app.set('port', process.env.PORT || 21019);
app.listen(app.get('port')); 

app.use(function(req, res, next) {
    if ((req.get('X-Forwarded-Proto') !== 'https')) {
        res.redirect('https://' + req.get('Host') + req.url);
    } else
    next();
});

Full app.js file

var express           = require('express');
var session           = require('express-session');
var cookieParser      = require('cookie-parser');
var bodyParser        = require('body-parser');
var logger            = require('morgan');
var path              = require('path');
var fileUpload        = require('express-fileupload');

var https             = require('https');

var app               = express();
var expressValidator  = require('express-validator');
var passport          = require('passport');
var flash             = require('connect-flash');

// - Cria rotas
var routes            = require('./routes/index');
var usuarios          = require('./routes/usuario');
var motorista         = require('./routes/motorista');
var login             = require('./routes/login');
var aluno             = require('./routes/aluno');
var contrato          = require('./routes/contrato');
var boleto            = require('./routes/boleto');
var pessoa            = require('./routes/pessoa');

require('./security/autenticacao')(passport);

app.use(logger('dev'));
app.use(expressValidator());
app.use(cookieParser());
app.use(bodyParser.json({limit: "50mb"}));
app.use(bodyParser.urlencoded({limit: "50mb", extended: true, parameterLimit:50000}));
app.use(express.static(path.join(__dirname, 'public')));
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
app.use(session({
    secret: 'reis&turlwaysrunning',
    resave: true,
    saveUninitialized: true
 } ));
app.use(logErrors);
app.use(passport.initialize());
app.use(passport.session());
app.use(flash());
app.use(function (req, res, next) {
    res.locals.login = req.user;
    next();
});
app.use(fileUpload());

app.set('port', process.env.PORT || 21019);
app.listen(app.get('port')); 

app.use(function(req, res, next) {
    if ((req.get('X-Forwarded-Proto') !== 'https')) {
        res.redirect('https://' + req.get('Host') + req.url);
    } else
    next();
});

// Atriui rotas
app.use('/home', routes);
app.use('/usuarios', usuarios);
app.use('/alunos', aluno);
app.use('/motoristas', motorista);
app.use('/contratos', contrato);
app.use('/login', login);
app.use('/boletos', boleto);
app.use('/pessoas', pessoa);

//app.listen(port);

function logErrors (err, req, res, next) {
    console.error('Troxa: ' + err.stack)
    next(err)
  }

module.exports = app;

I tried that too and it did not work

File app.js

https.createServer(function (req, res) {
    res.writeHead(200, {'Content-Type': 'text/plain'});
    res.write('Hello World!');
    res.end();
  }).listen(21019);

Full app.js file

    var express           = require('express');
    var session           = require('express-session');
    var cookieParser      = require('cookie-parser');
    var bodyParser        = require('body-parser');
    var logger            = require('morgan');
    var path              = require('path');
    var fileUpload        = require('express-fileupload');

    var https             = require('https');

    var app               = express();
    var expressValidator  = require('express-validator');
    var passport          = require('passport');
    var flash             = require('connect-flash');

    // - Cria rotas
    var routes            = require('./routes/index');
    var usuarios          = require('./routes/usuario');
    var motorista         = require('./routes/motorista');
    var login             = require('./routes/login');
    var aluno             = require('./routes/aluno');
    var contrato          = require('./routes/contrato');
    var boleto            = require('./routes/boleto');
    var pessoa            = require('./routes/pessoa');

    require('./security/autenticacao')(passport);

    app.use(logger('dev'));
    app.use(expressValidator());
    app.use(cookieParser());
    app.use(bodyParser.json({limit: "50mb"}));
    app.use(bodyParser.urlencoded({limit: "50mb", extended: true, parameterLimit:50000}));
    app.use(express.static(path.join(__dirname, 'public')));
    app.set('views', path.join(__dirname, 'views'));
    app.set('view engine', 'ejs');
    app.use(session({
        secret: 'reis&turlwaysrunning',
        resave: true,
        saveUninitialized: true
     } ));
    app.use(logErrors);
    app.use(passport.initialize());
    app.use(passport.session());
    app.use(flash());
    app.use(function (req, res, next) {
        res.locals.login = req.user;
        next();
    });
    app.use(fileUpload());

    https.createServer(function (req, res) {
    res.writeHead(200, {'Content-Type': 'text/plain'});
    res.write('Hello World!');
    res.end();
  }).listen(21019);

    // Atriui rotas
    app.use('/home', routes);
    app.use('/usuarios', usuarios);
    app.use('/alunos', aluno);
    app.use('/motoristas', motorista);
    app.use('/contratos', contrato);
    app.use('/login', login);
    app.use('/boletos', boleto);
    app.use('/pessoas', pessoa);

    //app.listen(port);

    function logErrors (err, req, res, next) {
        console.error('Troxa: ' + err.stack)
        next(err)
      }
Ger
  • 583
  • 2
  • 13
  • 35
  • Are you using any package like pm2 to run it on your server? And when you say it runs on HTTP, does it run on port 80 or some other port? – Kevin Prasanna R R Jan 20 '19 at 02:26
  • In the hosting package I hired at KingHost.com they use pm2. The default port is 21019 http as the call is http://softaction.com.br:21019/login but should work with https://softaction.com.br:21019/login You can open it in your browser if you want – Ger Jan 20 '19 at 02:41
  • First of all https.createServer takes key & cert. Check https://nodejs.org/api/https.html#https_https_createserver_options_requestlistener. Second, you didnt say you express server to use https. See https://gist.github.com/ryanhanwu/5321302 you will get an idea how to do that. – Jayadratha Mondal Jan 20 '19 at 02:42
  • Thank you, I'll see you here, thank you Jayadratha Mondal – Ger Jan 20 '19 at 02:44
  • How do I get these files ssl.key and ssl.crt ? – Ger Jan 20 '19 at 02:59
  • You can create you own. Check https://stackoverflow.com/q/19665863/2691619 – Jayadratha Mondal Jan 20 '19 at 03:13
  • You can also try PORT Forwarding from port 443 to any internal port (21019) in your case. But did you purchase the SSL certificate yet? It seems that kinghost.com itself does not have SSL on their site. If your app has to be secure, I would recommend Heroku. You will get a free SSL site, but you can also choose to add your domain. – Kevin Prasanna R R Jan 20 '19 at 03:30
  • The certificate enabled there in KingHost is Let's Encrypt – Ger Jan 20 '19 at 03:32

3 Answers3

0

You could try the method of implementing https with express as shown here Enabling HTTPS on express.js ?

  • Following this example, the private key and certificate files are loaded. I do not have and I do not know what these files are. – Ger Jan 20 '19 at 02:42
0

You need to have your https credential (i.e cert and key ) to use https. You can use this to generate the credentials

openssl req -newkey rsa:2048 -new -nodes -x509 -days 3650 -keyout key.pem -out cert.pem

var fs = require('fs');
var https = require('https');

var httpsServerOptions = {
  'key': fs.readFileSync('./https/key.pem'),
  'cert': fs.readFileSync('./https/cert.pem')
};


var express = require('express');
var app = express();

// your express configuration here


var httpsServer = https.createServer(httpsServerOptions, app);


httpsServer.listen(21019);
devamaz
  • 95
  • 1
  • 8
  • It did not work, I created and put the 2 files, cert.pem and key.pem in the project directory and I used var httpsOptions = { key: fs.readFileSync (path.join (__ dirname, "key.pem")) cert: fs.readFileSync (path.join (__ dirname, "cert.pem")) }; To capture – Ger Jan 20 '19 at 03:43
0

If free Let's Encrypt certificates are good enough for you, you could use Greenlock and get free SSL with automated renewal.

Greenlock: Free SSL, Automated HTTPS

Greenlock handles certificate issuance and renewal (via Let's Encrypt) and http => https redirection, out-of-the box.

Instead of calling .listen() from express, you just export your express app (or any node-http compatible function).

Simplified, that looks like this:

express-app.js:

var express = require('express');
var app = express();

app.use('/', function (req, res) {
  res.send({ msg: "Hello, Encrypted World!" })
});

// DO NOT DO app.listen()
// Instead export your app:
module.exports = app;

Then you can use node's http and https for your server, or you can use greenlock express, which sets it up for you:

server.js:

require('greenlock-express').create({
  // Let's Encrypt v2 is ACME draft 11
  version: 'draft-11'
, server: 'https://acme-v02.api.letsencrypt.org/directory'

  // You MUST change these to valid email and domains
, email: 'john.doe@example.com'
, approveDomains: [ 'example.com', 'www.example.com' ]
, agreeTos: true

  // This should be the directory to which certificates are saved
, configDir: "/path/to/project/acme/"

, app: require('./express-app.js')

, communityMember: true // Get notified of important updates
, telemetry: true       // Contribute telemetry data to the project
}).listen(80, 443);

Screencast

Watch the QuickStart demonstration: https://youtu.be/e8vaR4CEZ5s

More Info

See https://stackoverflow.com/a/51146209/151312

coolaj86
  • 74,004
  • 20
  • 105
  • 125