How to set up an SSL certificate for an application that runs on Express?

Asked

Viewed 1,529 times

0

How to set up an SSL certificate for an application that runs on Express?

I’m trying to set up the Express server I created, to pass the SSL certificate and go from http to https.

I read the Express documentation, but I can’t find the solution. They proposed things to me like Lets Encrypt, but it doesn’t support Node.js. I don’t know if I should modify the hosts file, which I’ve already modified to run the application, or what I have to do. I saw a form, but it only works on the Unix system. I show you the way in which I set up the server file, in case they can help me, it took three days looking for ways to do it without success. The ones I saw do not support Node.js. Thank you

Citation I edit it again: Sorry, forget to say that my goal is to create the certificate for an application in which you can register on Facebook and tried the methods that my colleagues kindly offered, but it did not work thanks to the new Facebook policy. If you have another idea, my domain would be michaelgram.test thank you and forgive the inconvenience, for not doing the question well.

let express = require('express');
let aws = require('aws-sdk');
let multer = require('multer');
let multerS3 = require('multer-s3');
let ext = require('file-extension');
let cookieParser = require('cookie-parser');
let bodyParser = require('body-parser');
let expressSession = require('express-session');
let passport = require('passport');
let michaelgram = require('michaelgram-client');
let auth = require('./auth')
let config = require('./config');
let port = process.env.PORT || 5050;

let client = michaelgram.createClient(config.client);

let s3 = new aws.S3({
  accessKeyId: config.aws.accessKey,
  secretAccessKey: config.aws.secretKey
});

let storage = multerS3({
  s3: s3,
  bucket: 'michaelgram',
  acl: 'public-read',
  metadata: function (req, file, cb) {
    cb(null, { fieldName: file.fieldname })
  },
  key: function (req, file, cb) {
    cb(null, +Date.now() + '.' + ext(file.originalname))
  }
});


let upload = multer({ storage: storage }).single('picture');

let app = express();

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(expressSession({
  secret: config.secret,
  resave: false,
  saveUninitialized: false
}))
app.use(passport.initialize())
app.use(passport.session())
app.set('view engine', 'pug');
app.use(express.static('public'));

passport.use(auth.localStrategy);
passport.use(auth.facebookStrategy);
passport.deserializeUser(auth.deserializeUser);
passport.serializeUser(auth.serializeUser);

app.get('/', function (req, res) {
  res.render('index', { title: 'Michaelgram' });
})

app.get('/signup', function (req, res) {
  res.render('index', { title: 'Michaelgram - Signup' });
})

app.post('/signup', function (req, res) {
  let user = req.body;
  client.saveUser(user, function (err, usr) {
    if (err) return res.status(500).send(err.message)
    debugger
    res.redirect('/signin');
  });
});

app.get('/signin', function (req, res) {
  res.render('index', { title: 'Michaelgram - Signin' });
})

app.post('/login', passport.authenticate('local', {
  successRedirect: '/',
  failureRedirect: '/signin'
}));

app.get('/auth/facebook', passport.authenticate('facebook', { scope: 'email' }));

app.get('/auth/facebook/callback', passport.authenticate('facebook', {
  successRedirect: '/',
  failureRedirect: '/signin'
}));

function ensureAuth (req, res, next) {
  if (req.isAuthenticated()) {
    return next()
  }

  res.status(401).send({ error: 'not authenticated' })
}

app.get('/api/pictures', function (req, res, next) {
  let pictures = [ ];

  setTimeout(function () {
    res.send(pictures);
  }, 2000)
});

app.post('/api/pictures', ensureAuth,function (req, res) {
  upload(req, res, function (err) {
    if (err) {
      return res.send(500, "Error uploading file");
    }
    res.send('File uploaded');
  })
})

app.get('/api/user/:username', (req, res) => {
  const user = {
    username: 'miguelito',
    avatar: '',
    pictures: [  ]
  }

  res.send(user);
})

app.get('/:username', function (req, res) {
  res.render('index', { title: `Michaelgram - ${req.params.username}` });
})

app.get('/:username/:id', function (req, res) {
  res.render('index', { title: `Michaelgram - ${req.params.username}` });
})

app.listen(port, function (err) {
  if (err) return console.log('Hubo un error'), process.exit(1);

  console.log('Michaelgram escuchando en el puerto 5050');
})

2 answers

2

I have an example that uses both http and https. Since version 3 of express you can use the following code:

var fs = require('fs');
var http = require('http');
var https = require('https');
var privateKey  = fs.readFileSync('keys/key.key', 'utf8');
var certificate = fs.readFileSync('keys/cert.crt', 'utf8');


var credentials = {key: privateKey, cert: certificate};
var express = require('express');
var app = express();

// your express configuration here
app.get('/', function(req,res) {
    res.send('hello');
});

var httpServer = http.createServer(app);
var httpsServer = https.createServer(credentials, app);

httpServer.listen(8080, function () {
    console.log("JSON Server is running on  http://localhost:" + 8080);
});
httpsServer.listen(8443, function () {
    console.log("JSON Server is running on  https://localhost:" + 8443);
});

You just need the key.key and cert.crt to run on your machine.

I hope I’ve helped

1

This video author teach you how to deploy a Node application with ssl and Nginx: https://www.youtube.com/watch?v=kR06NoSzAXY

There’s the guy’s blog with the copy and paste commands, and I put the link to the video: https://code.lengstorf.com/deploy-nodejs-ssl-digitalocean/

Explaining what you’re gonna do:

Install and configure Node, your db and your app normally;

Go install the certbot;

As the certbot does not recognize the Node, you will have to use something he knows, in case the Nginx https://pt.wikipedia.org/wiki/Nginx

It acts as load balancer and reverse proxy for the requests and the best is the fact that it works with certbot.

By the Nginx you will order the requests on port 80 for your app on port 443 that is with SSL, in the links it teaches to take an A+ in SSL configuration.

  • Thank you, the computer where work was broken, when I solved, I start trying. Thank you

Browser other questions tagged

You are not signed in. Login or sign up in order to post.