Muhammad Raihan Muhaimin
Muhammad Raihan Muhaimin

Reputation: 5729

Implementing a https server on sailjs

Hi I am creating some rest api for sailjs application. Now I need to access my application using OAuth2.0 authentication with http-bearer-token strategy. So I want my server to accept https connection. Any hint how I can do that?

Upvotes: 1

Views: 184

Answers (2)

Finn
Finn

Reputation: 2775

In the production environment, we should not let the nodejs app face the raw traffic. Use Nginx instead, Nginx can handle the https connection and forward to sailjs http connection, additional handle the rate limit, cache...

server {
    listen 443 ssl;
    server_name localhost;

    ssl on;
    ssl_certificate /etc/nginx/your_site/your_site-bundle.crt;
    ssl_certificate_key /etc/nginx/your_site/your_site.key;

    location /your_api {
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header Host $http_host;
        proxy_set_header X-NginX-Proxy true;
        proxy_pass http://127.0.0.1:2000;
        proxy_redirect off;
    }
}

It also handles the http and https connections in the same time. In the sample below, I just forward http connection to https. If you have another purpose, just change the logic inside.

server {
    listen 80;
    server_name localhost;
    return 301 https://$host$request_uri;
}

Upvotes: 0

bredikhin
bredikhin

Reputation: 9035

It turns out to be pretty simple, actually. Update your config/local.js with the following:

/**
 * Depencencies
 */
var fs = require('fs');

module.exports = {
  // ...
  // Here go the port, environment definitions, etc.
  // ...

  ssl: {
    key: fs.readFileSync('path_to_your_key.pem'),
    cert: fs.readFileSync('path_to_your_cert.pem')
  }
};

To play with it in development environment, you can just create a self-signed certificate, put those files in config/ssl and in config/local.js use

  ssl: {
    key: fs.readFileSync(__dirname + 'ssl/key.pem'),
    cert: fs.readFileSync(__dirname + 'ssl/cert.pem')
  }

Upvotes: 3

Related Questions