Saturday 29 April 2017

Generate SSL certificates for HTTPS in node.js

My machine uses windows 8.1. And I want to generate an SSL certificate for Https requests. In this exercise I am using Node.js and Express.js. Here are my steps.

1) I am going to my project's folder and I am setting the paths for SSL.

set OPEN_SSL=c:OpenSSL-Win64\openssl.cfg

set RANDFILE=c:\Users\Theodosios\Desktop\NodeJs_Coursera\Node_Js\rest-server-
passport\bin\.rnd*

2) Next I am typing

 set OPEN_SSL=c:OpenSSL-Win64\openssl.cfg

to open the OpenSSL console.

3) I am creating a private key,put my details(country,location,company's name etc,and finally I am generating a certificate.

openssl genrsa 1024 private.key

openssl req -new -key private.key -out cert.csr

openssl x509 -req -in cert.csr -signkey private.key -out certificate.pem

Now I am going to show you two files from express.

www

        #!/usr/bin/env node
        /**
         * Module dependencies.
         */

        var app = require('../app');
        var debug = require('debug')('rest-server:server');
        var http = require('http');
        var https = require('https');
        var fs = require('fs');

        /**
         * Get port from environment and store in Express.
         */

        var port = normalizePort(process.env.PORT || '3000');

        app.set('port', port);
        app.set('secPort',port+443);

        /**
         * Create HTTP server.
         */

        var server = http.createServer(app);

        /**
         * Listen on provided port, on all network interfaces.
         */

        server.listen(port, function() {
           console.log('Server listening on port ',port);
        });
        server.on('error', onError);
        server.on('listening', onListening);

        /**
         * Create HTTPS server.
         */ var options = {
          key: fs.readFileSync(__dirname+'/private.key'),
          cert: fs.readFileSync(__dirname+'/certificate.pem')
        };

        var secureServer = https.createServer(options,app);

        /**
         * Listen on provided port, on all network interfaces.
         */

        secureServer.listen(app.get('secPort'), function() {
           console.log('Server listening on port ',app.get('secPort'));
        });
        secureServer.on('error', onError);
        secureServer.on('listening', onListening);

        /**
         * Normalize a port into a number, string, or false.
         */

        function normalizePort(val) {
          var port = parseInt(val, 10);
          if (isNaN(port)) {
            // named pipe
            return val;
          }
          if (port >= 0) {
            // port number
            return port;
          }
          return false;
        }

        /**
         * Event listener for HTTP server "error" event.
         */

        function onError(error) {
          if (error.syscall !== 'listen') {
            throw error;
          }
          var bind = typeof port === 'string'
            ? 'Pipe ' + port
            : 'Port ' + port;

          // handle specific listen errors with friendly messages
          switch (error.code) {
            case 'EACCES':
              console.error(bind + ' requires elevated privileges');
              process.exit(1);
              break;

            case 'EADDRINUSE':
              console.error(bind + ' is already in use');
              process.exit(1);
              break;

            default:
              throw error;
          }
        }

        /**
         * Event listener for HTTP server "listening" event.
         */

        function onListening() {
          var addr = server.address();
          var bind = typeof addr === 'string'
            ? 'pipe ' + addr
            : 'port ' + addr.port;
          debug('Listening on ' + bind);
        }

app.js

            var express = require('express');
            var path = require('path');
            var favicon = require('serve-favicon');
            var logger = require('morgan');
            var cookieParser = require('cookie-parser');
            var bodyParser = require('body-parser');
            var mongoose = require('mongoose');
            var passport = require('passport');
            var LocalStrategy = require('passport-local').Strategy;

            var config = require('./config');

            mongoose.connect(config.mongoUrl);
            var db = mongoose.connection;
            db.on('error', console.error.bind(console, 'connection error:'));
            db.once('open', function () {
                // we're connected!
                console.log("Connected correctly to server");
            });

            var routes = require('./routes/index');
            var users = require('./routes/users');
            var dishRouter = require('./routes/dishRouter');
            var promoRouter = require('./routes/promoRouter');
            var leaderRouter = require('./routes/leaderRouter');

            var app = express();
            // Secure traffic only
            app.all('*', function(req, res, next){
                console.log('req start: ',req.secure, req.hostname, req.url, app.get('port'));
              if (req.secure) {
                return next();
              };

             res.redirect('https://'+req.hostname+':'+app.get('secPort')+req.url);
            });
            // Secure traffic only
            app.all('*', function(req, res, next){
                console.log('req start: ',req.secure, req.hostname, req.url, app.get('port'));
              if (req.secure) {
                return next();
              };

             res.redirect('https://'+req.hostname+':'+app.get('secPort')+req.url);
            });
            // view engine setup
            app.set('views', path.join(__dirname, 'views'));
            app.set('view engine', 'jade');
            // uncomment after placing your favicon in /public
            //app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));

            app.use(logger('dev'));
            app.use(bodyParser.json());
            app.use(bodyParser.urlencoded({ extended: false }));
            app.use(cookieParser());

            // passport config
            var User = require('./models/user');
            app.use(passport.initialize());
            passport.use(new LocalStrategy(User.authenticate()));
            passport.serializeUser(User.serializeUser());
            passport.deserializeUser(User.deserializeUser());

            app.use(express.static(path.join(__dirname, 'public')));

            app.use('/', routes);
            app.use('/users', users);
            app.use('/dishes',dishRouter);
            app.use('/promotions',promoRouter);
            app.use('/leadership',leaderRouter);

            // catch 404 and forward to error handler
            app.use(function(req, res, next) {
              var err = new Error('Not Found');
              err.status = 404;
              next(err);
            });

            // error handlers
            // development error handler
            // will print stacktrace
            if (app.get('env') === 'development') {
              app.use(function(err, req, res, next) {
                res.status(err.status || 500);
                res.json({
                  message: err.message,
                  error: err
                });
              });
            }

            // production error handler
            // no stacktraces leaked to user
            app.use(function(err, req, res, next) {
              res.status(err.status || 500);
              res.json({
                message: err.message,
                error: {}
              });
            });

            module.exports = app;

Basically the https requests are directed to port 3443. Finally I start I am starting my express server by nmp start.

I open my browser and type

https://MY_IP_GOES_HERE/3443

and I am this message.

ERR_CONNECTION_REFUSED

From my research,I found out that I should change DNS values. But in my case,this didn't work. Please advice.

Thanks,

Theo.



via Theo

No comments:

Post a Comment