在sails js上实现https服务器

时间:2014-01-30 02:58:09

标签: node.js ssl express https sails.js

您好我正在为sailjs应用程序创建一些rest api。现在我需要使用带有http-bearer-token策略的OAuth2.0身份验证来访问我的应用程序。所以我希望我的服务器接受https连接。有什么提示我怎么能这样做?

2 个答案:

答案 0 :(得分:3)

实际上,结果很简单。使用以下内容更新config/local.js

/**
 * 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')
  }
};

要在开发环境中使用它,您只需create a self-signed certificate,将这些文件放在config/sslconfig/local.js中使用

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

答案 1 :(得分:0)

在生产环境中,我们不应让nodejs应用程序面对原始流量。使用Nginx代替,Nginx可以处理https连接并转发到sailjs http连接,额外处理速率限制,缓存......

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;
    }
}

它还可以同时处理http和https连接。在下面的示例中,我只是将http连接转发到https。如果你有其他目的,只需更改内部逻辑。

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