node.js 为本地主机创建一个可信的自签名 SSL 证书(用于 Express/Node)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21397809/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 16:45:54  来源:igfitidea点击:

create a trusted self-signed SSL cert for localhost (for use with Express/Node)

node.jsexpressopenssllocalhostssl-certificate

提问by JasonS

Trying to follow various instructions on creating a self-signed cert for use with localhost, Most of the instructions seem to be for IIS, but I'm trying to use Nodejs/Express. None of them work properly because while the cert gets installed, it is not trusted. here's what I've tried that fails:

尝试按照有关创建与本地主机一起使用的自签名证书的各种说明进行操作,大多数说明似乎适用于 IIS,但我正在尝试使用 Nodejs/Express。它们都不能正常工作,因为在安装证书时,它不受信任。这是我尝试过但失败的方法:

Can someone offer a workflow that can do this? I can get a cert installed, butI can't get the cert to be trusted in either chrome (v32) or IE (v10).

有人可以提供可以做到这一点的工作流程吗? 我可以安装证书,但我无法在 chrome (v32) 或 IE (v10) 中获得可信任的证书。

EDIT: it was suggested in comments that the problem is no trusted cert-root. I installed the cert via IE but it's still not being trusted.

编辑:在评论中建议问题是没有受信任的证书根。我通过 IE 安装了证书,但它仍然不受信任。

采纳答案by AIon

The answers above were partial. I've spent so much time getting this working, it's insane. Note to my future self, here is what you need to do:

上面的答案是片面的。我花了很多时间让这个工作,这太疯狂了。请注意我未来的自己,这是您需要做的:

I'm working on Windows 10, with Chrome 65. Firefox is behaving nicely - just confirm localhost as a security exception and it will work. Chrome doesn't:

我正在使用 Chrome 65 的 Windows 10。Firefox 运行良好 - 只需确认 localhost 作为安全例外,它就会工作。Chrome 不会:

Step 1.in your backend, create a folder called security. we will work inside it.

步骤 1.在您的后端,创建一个名为security. 我们将在里面工作。

Step 2.create a request config file named req.cnfwith the following content (credit goes to: @Anshul)

步骤 2.创建一个以req.cnf以下内容命名的请求配置文件(归功于:@Anshul

req.cnf :

请求.cnf :

[req]
distinguished_name = req_distinguished_name
x509_extensions = v3_req
prompt = no
[req_distinguished_name]
C = Country initials like US, RO, GE
ST = State
L = Location
O = Organization Name
OU = Organizational Unit 
CN = www.localhost.com
[v3_req]
keyUsage = critical, digitalSignature, keyAgreement
extendedKeyUsage = serverAuth
subjectAltName = @alt_names
[alt_names]
DNS.1 = www.localhost.com
DNS.2 = localhost.com
DNS.3 = localhost

An explanation of this fields is here.

这个字段的解释是here

Step 3.navigate to the security folder in the terminal and type the following command :

步骤 3.导航到终端中的安全文件夹并键入以下命令:

openssl req -x509 -nodes -days 365 -newkey rsa:2048 -keyout cert.key -out cert.pem -config req.cnf -sha256

openssl req -x509 -nodes -days 365 -newkey rsa:2048 -keyout cert.key -out cert.pem -config req.cnf -sha256

Step 4.then outside of securityfolder, in your express app do something like this: (credit goes to @Diego Mello)

第 4 步。然后在security文件夹之外,在您的 Express 应用程序中执行以下操作:(归功于 @Diego Mello)

backend 
 /security
 /server.js

server.js:

服务器.js:

const express = require('express')
const app = express()
const https = require('https')
const fs = require('fs')
const port = 3000

app.get('/', (req, res) => {
    res.send("IT'S WORKING!")
})

const httpsOptions = {
    key: fs.readFileSync('./security/cert.key'),
    cert: fs.readFileSync('./security/cert.pem')
}
const server = https.createServer(httpsOptions, app)
    .listen(port, () => {
        console.log('server running at ' + port)
    })

Step 5.start the server, node server.js, and go to https://localhost:3000.

步骤 5.启动服务器,node server.js然后转到https://localhost:3000

At this point we have the server setup. But the browser should show a warning message.

此时我们已经设置了服务器。但浏览器应显示警告消息。

We need to register our self-signed certificate, as a CA trusted Certificate Authority, in the chrome/windows certificates store.(chrome also saves this in windows,)

我们需要在 chrome/windows 证书存储中注册我们的自签名证书,作为 CA 信任的证书颁发机构。(chrome 也将其保存在 Windows 中,)

Step 6.open Dev Tools in chrome, go to Security panel, then click on View Certificate. enter image description here

步骤 6.在 Chrome 中打开 Dev Tools,转到安全面板,然后单击查看证书。 在此处输入图片说明

Step 7.go to Details panel, click Copy File, then when the Certificate Export Wizard appears, click Next as below:

步骤 7.转到详细信息面板,单击复制文件,然后出现证书导出向导时,单击下一步,如下所示:

go to details - copy file - next on export wizard

go to details - copy file - next on export wizard

Step 8.leave DER encoding, click next, choose Browse, put it on a easy to access folder like Desktop, and name the certificate localhost.cer, then click Save and then Finish.. You should be able to see your certificate on Desktop.

步骤8.离开DER编码,点击下一步,选择Browse,放在像桌面这样易于访问的文件夹中,并将证书命名为localhost.cer, then click Save and then Finish.。您应该能够在桌面上看到您的证书。

Step 9.Open chrome://settings/by inserting it in the url box. Down below, click on Advanced / Advanced Options, then scroll down to find Manage Certificates.

步骤9打开chrome://settings/通过在URL框中插入。在下方,单击Advanced / Advanced Options,然后向下滚动以查找Manage Certificates

choose manage certificates

choose manage certificates

Step 10.Go to Trusted Root Certification Authorities panel, and click import.

步骤 10.转到受信任的根证书颁发机构面板,然后单击导入。

Go to Trusted Root Certification Authorities panel, and click import

Go to Trusted Root Certification Authorities panel, and click import

We will import the localhost.cercertificate we just finished exporting in step 8.

我们将导入localhost.cer我们刚刚在步骤 8 中导出的证书。

Step 11.click browse, find the localhost.cer, leave the default values click next a bunch of times - until this warning appears, click yes.

步骤 11.单击浏览,找到localhost.cer,保留默认值单击下一步 - 直到出现此警告,单击是。

confirm security exception

confirm security exception

Step 12.close everything, and restart chrome. Then, when going to https://localhost:3000you should see: gotta love the green

步骤 12.关闭所有内容,然后重新启动 chrome。然后,去的时候https://localhost:3000你应该看到: gotta love the green

回答by Diego Mello

Shortest way.Tested on MacOS, but may work similarly on other OS.

最短的路。在 MacOS 上测试过,但在其他操作系统上可能类似。

Generate pem

生成pem

> openssl req -x509 -newkey rsa:2048 -keyout keytmp.pem -out cert.pem -days 365

> openssl rsa -in keytmp.pem -out key.pem

Your express server

您的快递服务器

const express = require('express')
const app = express()
const https = require('https')
const fs = require('fs')
const port = 3000

app.get('/', (req, res) => {
  res.send('WORKING!')
})

const httpsOptions = {
  key: fs.readFileSync('./key.pem'),
  cert: fs.readFileSync('./cert.pem')
}
const server = https.createServer(httpsOptions, app).listen(port, () => {
  console.log('server running at ' + port)
})
  • Open https://localhost:3000in Google Chrome and you'll see that it's not secure. Yet!
  • In Developer Tools > Security > View Certificate: Drag image to your desktop and double click it.
  • Click 'Add'
  • Find it in Keychain Access and double click it
  • Expand 'Trust' and change 'When using this certificate' to 'Always trust'.
  • You may be prompted to authenticate.
  • Restart your server.
  • Refresh your browser.
  • Enjoy! :)
  • https://localhost:3000在谷歌浏览器中打开,你会发现它不安全。然而!
  • 在开发者工具 > 安全 > 查看证书中:将图像拖到桌面并双击它。
  • 点击“添加”
  • 在 Keychain Access 中找到它并双击它
  • 展开“信任”并将“使用此证书时”更改为“始终信任”。
  • 系统可能会提示您进行身份验证。
  • 重新启动您的服务器。
  • 刷新浏览器。
  • 享受!:)

回答by Diego Mello

You can try openSSL to generate certificates. Take a look at this.

您可以尝试使用 openSSL 生成证书。看看这个

You are going to need a .key and .crt file to add HTTPS to node JS express server. Once you generate this, use this code to add HTTPS to server.

您将需要一个 .key 和 .crt 文件来将 HTTPS 添加到 node JS express 服务器。生成此代码后,请使用此代码将 HTTPS 添加到服务器。

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

var options = {
    key: fs.readFileSync('/etc/apache2/ssl/server.key'),
    cert: fs.readFileSync('/etc/apache2/ssl/server.crt'),
    requestCert: false,
    rejectUnauthorized: false
};


var app = express();

var server = https.createServer(options, app).listen(3000, function(){
    console.log("server started at port 3000");
});

This is working fine in my local machine as well as the server where I have deployed this. The one I have in server was bought from goDaddy but localhost had a self signed certificate.

这在我的本地机器以及我部署它的服务器上运行良好。我在服务器中的那个是从 goDaddy 购买的,但 localhost 有一个自签名证书。

However, every browser threw an error saying connection is not trusted, do you want to continue. After I click continue, it worked fine.

但是,每个浏览器都抛出一个错误,说连接不受信任,您要继续吗?单击继续后,它工作正常。

If anyone has ever bypassed this error with self signed certificate, please enlighten.

如果有人用自签名证书绕过了这个错误,请指教。

回答by fuma

How to generate an SSL certificate for localhost: link

如何为本地主机生成 SSL 证书:链接

openssl genrsa -des3 -out server.key 1024

you need to enter a passwordhere which you need to retype in the following steps

您需要在此处输入密码,您需要在以下步骤中重新输入密码

openssl req -new -key server.key -out server.csr

when asked "Common Name" type in: localhost

当被问到“通用名称”时,输入:localhost

openssl x509 -req -days 1024 -in server.csr -signkey server.key -out server.crt

回答by TroyWorks

Here's what's working for me

这对我有用

on windows

在窗户上

1) Add this to your %WINDIR%\System32\drivers\etc\hosts file: 127.0.0.1 localdev.YOURSITE.net(cause browser have issues with 'localhost' (for cross origin scripting)

1) 将此添加到您的 %WINDIR%\System32\drivers\etc\hosts 文件中:127.0.0.1 localdev.YOURSITE.net(因为浏览器有“localhost”问题(用于跨源脚本)

Windows Vista and Windows 7 Vista and Windows 7 use User Account Control (UAC) so Notepad must be run as Administrator.

Windows Vista 和 Windows 7 Vista 和 Windows 7 使用用户帐户控制 (UAC),因此记事本必须以管理员身份运行。

  1. Click Start -> All Programs -> Accessories

  2. Right click Notepad and select Run as administrator

  3. Click Continue on the "Windows needs your permission" UAC window.

  4. When Notepad opens Click File -> Open

  5. In the filename field type C:\Windows\System32\Drivers\etc\hosts

  6. Click Open

  7. Add this to your %WINDIR%\System32\drivers\etc\hosts file: 127.0.0.1 localdev.YOURSITE.net

  8. Save

  9. Close and restart browsers

  1. 点击开始 -> 所有程序 -> 附件

  2. 右键单击记事本并选择以​​管理员身份运行

  3. 单击“Windows 需要您的许可”UAC 窗口上的继续。

  4. 记事本打开时单击文件-> 打开

  5. 在文件名字段中键入 C:\Windows\System32\Drivers\etc\hosts

  6. 点击打开

  7. 将此添加到您的 %WINDIR%\System32\drivers\etc\hosts 文件中:127.0.0.1 localdev.YOURSITE.net

  8. 节省

  9. 关闭并重新启动浏览器

On Mac or Linux:

在 Mac 或 Linux 上:

  1. Open /etc/hosts with supermission
  2. Add 127.0.0.1 localdev.YOURSITE.net
  3. Save it
  1. su权限打开 /etc/hosts
  2. 添加 127.0.0.1 localdev.YOURSITE.net
  3. 保存

When developing you use localdev.YOURSITE.net instead of localhost so if you are using run/debug configurations in your ide be sure to update it.

在开发时,您使用 localdev.YOURSITE.net 而不是 localhost,因此如果您在 ide 中使用运行/调试配置,请务必更新它。

Use ".YOURSITE.net" as cookiedomain (with a dot in the beginning) when creating the cookiem then it should work with all subdomains.

在创建 cookiem 时使用“.YOURSITE.net”作为 cookiedomain(以点开头),然后它应该适用于所有子域。

2) create the certificate using that localdev.url

2) 使用该 localdev.url 创建证书

TIP: If you have issues generating certificates on windows, use a VirtualBox or Vmware machine instead.

提示:如果您在 Windows 上生成证书时遇到问题,请改用 VirtualBox 或 Vmware 机器。

3) import the certificate as outlined onhttp://www.charlesproxy.com/documentation/using-charles/ssl-certificates/

3) 导入http://www.charlesproxy.com/documentation/using-charles/ssl-certificates/ 上概述的证书

回答by som

Mkcertfrom @FiloSottile makes this process infinitely simpler:

@FiloSottile的 Mkcert 使这个过程无限简单:

  1. Install mkcert, there are instructions for macOS/Windows/Linux
  2. mkcert -installto create a local CA
  3. mkcert localhost 127.0.0.1 ::1to create a trusted cert for localhost in the current directory
  4. You're using node (which doesn't use the system root store), so you need to specify the CA explicitlyin an environment variable, e.g: export NODE_EXTRA_CA_CERTS="$(mkcert -CAROOT)/rootCA.pem"
  5. Finally run your express server using the setup described in various other answers (e.g. below)
  6. boom. localhost's swimming in green.
  1. 安装mkcert,macOS/Windows/Linux 有说明
  2. mkcert -install创建本地 CA
  3. mkcert localhost 127.0.0.1 ::1在当前目录中为 localhost 创建可信证书
  4. 您正在使用节点(它不使用系统根存储),因此您需要在环境变量中明确指定 CA,例如:export NODE_EXTRA_CA_CERTS="$(mkcert -CAROOT)/rootCA.pem"
  5. 最后使用各种其他答案中描述的设置运行您的快速服务器(例如下面)
  6. 繁荣。本地主机的绿色游泳。

Basic node setup:

基本节点设置:

const https = require('https');
const fs = require('fs');
const express = require('express');

const app = express();    
const server = https.createServer({
    key: fs.readFileSync('/XXX/localhost+2-key.pem'), // where's me key?
    cert: fs.readFileSync('/XXX/localhost+2.pem'), // where's me cert?
    requestCert: false,
    rejectUnauthorized: false,
}, app).listen(10443); // get creative

回答by Vijay Rudraraju

If you're on OSX/Chrome you can add the self-signed SSL certificate to your system keychain as explained here: http://www.robpeck.com/2010/10/google-chrome-mac-os-x-and-self-signed-ssl-certificates

如果您使用的是 OSX/Chrome,您可以将自签名 SSL 证书添加到您的系统钥匙串中,如下所述:http: //www.robpeck.com/2010/10/google-chrome-mac-os-x-and -自签名SSL证书

It's a manual process, but I got it working finally. Just make sure the Common Name (CN) is set to "localhost" (without the port) and after the certificate is added make sure all the Trust options on the certificate are set to "Always Trust". Also make sure you add it to the "System" keychain and not the "login" keychain.

这是一个手动过程,但我终于让它工作了。只需确保通用名称 (CN) 设置为“localhost”(不带端口),并在添加证书后确保证书上的所有信任选项都设置为“始终信任”。还要确保将它添加到“系统”钥匙串而不是“登录”钥匙串。

回答by B T

If you're using node, why not generate them with node? This module seems to be pretty full featured:

如果您正在使用节点,为什么不使用节点生成它们?这个模块似乎功能齐全:

Note that I wouldn't generate on the fly. Generate with some kind of build script so you have a consistent certificate and key. Otherwise you'll have to authorize the newly generated self-signed certificate every time.

请注意,我不会即时生成。使用某种构建脚本生成,以便您拥有一致的证书和密钥。否则,您每次都必须授权新生成的自签名证书。

回答by tomo

Some of the answers posted have pieces that were very useful to me to overcome this problem too. However, I was also interested in the minimumnumber of steps and, ideally, avoiding OpenSSL (on Windows 10).

发布的一些答案也对我克服这个问题非常有用。但是,我也对最少的步骤数感兴趣,并且最好避免使用 OpenSSL(在 Windows 10 上)。

So, one critical piece from the answers (credit: @TroyWorks) is that you need to edit your HOSTS file to create a fictitious server, and map that to 127.0.0.1. This assumes you are going to be doing local development.

因此,答案中的一个关键部分(来源:@ TroyWorks)是您需要编辑您的 HOSTS 文件以创建一个虚构的服务器,并将其映射到 127.0.0.1。这假设您将进行本地开发。

In my case, I was using the SS certificate to secure a websocket in NodeJS, and that socket was being connected to programmatically (as opposed to via browser). So for me, it was critical that the certificate be accepted without warnings or errors, and the critical piece there was to get the cert created with a proper CN (and of course accept the cert into Trusted Authorities, as described elsewhere in the answers). Using IIS to create a self-signed cert won't create the proper CN, so I discovered the following simplecommand using Powershell:

就我而言,我使用 SS 证书来保护 NodeJS 中的 websocket,并且该套接字以编程方式连接(而不是通过浏览器)。所以对我来说,在没有警告或错误的情况下接受证书是至关重要的,而关键部分是使用适当的 CN 创建证书(当然,将证书接受到受信任的机构,如答案中的其他地方所述) . 使用 IIS 创建自签名证书不会创建正确的 CN,因此我使用 Powershell发现了以下简单命令:

New-SelfSignedCertificate -DnsName "gandalf.dummy.dev" -FriendlyName "gandalf" -CertStoreLocation "cert:\LocalMachine\My"

This has to be run in the PS Admin console, but it simply works, and puts the cert into the "Personal" section of the LocalMachine certificate store. You can verify it got created by executing:

这必须在 PS 管理控制台中运行,但它只是有效,并将证书放入 LocalMachine 证书存储的“个人”部分。您可以通过执行以下命令来验证它是否已创建:

ls cert:\LocalMachine\My 

To trust it, simply copy this and paste into "Trusted Root Certification Authorities" using Certificate Manager (making sure you are looking at the Local Machine certificates, not Current User!).

要信任它,只需使用证书管理器将其复制并粘贴到“受信任的根证书颁发机构”中(确保您正在查看本地机器证书,而不是当前用户!)。

If you bind to this certificate in IIS, you should be able to hit https://gandalf.dummy.dev/and get a secure connection without any warnings.

如果您在 IIS 中绑定到此证书,您应该能够点击https://gandalf.dummy.dev/并获得安全连接,而不会出现任何警告。

The final piece, using this in NodeJS, is described above and in other SO answers, so I'll only add that on Windows, it is easier to work with a pfx file that combines the cert and private key. You can export a pfx easily from the Certificate Manager, but it does affect how you use it in NodeJS. When instantiating a Server using the 'https' module, the options you would use (instead of 'key' and 'cert') would be 'pfx' and 'passphrase', as in:

最后一部分,在 NodeJS 中使用它,在上面和其他 SO 答案中进行了描述,所以我只会在 Windows 上添加它,使用结合了证书和私钥的 pfx 文件更容易。您可以轻松地从证书管理器导出 pfx,但它确实会影响您在 NodeJS 中使用它的方式。使用“https”模块实例化服务器时,您将使用的选项(而不是“key”和“cert”)将是“pfx”和“passphrase”,如下所示:

var https = require('https');
var options = { 
    pfx: fs.readFileSync('mypfxfile'), 
    passphrase: 'foo' 
};
var server = https.createServer(options);

回答by mushcraft

on windows I made the iis development certificate trusted by using MMC (start > run > mmc), then add the certificate snapin, choosing "local computer" and accepting the defaults. Once that certificate snapip is added expand the local computer certificate tree to look under Personal, select the localhost certificate, right click > all task > export. accept all defaults in the exporting wizard.

在 Windows 上,我使用 MMC(开始 > 运行 > mmc)使 iis 开发证书受信任,然后添加证书管理单元,选择“本地计算机”并接受默认值。添加该证书 snapip 后,展开本地计算机证书树以查看 Personal 下,选择 localhost 证书,右键单击 > 所有任务 > 导出。接受导出向导中的所有默认值。

Once that file is saved, expand trusted certificates and begin to import the cert you just exported. https://localhostis now trusted in chrome having no security warnings.

保存该文件后,展开受信任的证书并开始导入您刚刚导出的证书。https://localhost现在信任 chrome,没有安全警告。

I used this guide resolution #2from the MSDN blog, the op also shared a link in his question about that also should using MMC but this worked for me. resolution #2

我使用了 MSDN 博客中的指南解决方案 #2,操作员还在他的问题中分享了一个链接,该链接也应该使用 MMC,但这对我有用。 决议#2