JasonS
JasonS

Reputation: 7733

Create a trusted self-signed SSL certificate for 'localhost' (for use with Express.js and Node.js)

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

Is there a workflow that can do this? I can get a certificate installed, but I can't get the certificate to be trusted in either Google Chrome (v32) or Internet Explorer (v10).

It was suggested in comments that the problem is no trusted cert-root. I installed the certificate via Internet Explorer, but it's still not being trusted.

Upvotes: 206

Views: 252403

Answers (19)

tomo
tomo

Reputation: 1522

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 minimum number of steps and, ideally, avoiding OpenSSL (on 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.

In my case, I was using the SS certificate to secure a websocket in Node.js, 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 certificate won't create the proper CN, so I discovered the following simple command using Powershell:

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

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

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.

The final piece, using this in Node.js, 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 certificate and private key. You can export a pfx easily from the Certificate Manager, but it does affect how you use it in Node.js. 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:

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

Upvotes: 7

AIon
AIon

Reputation: 13081

The previous answers 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:

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

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

File req.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.

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

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

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

backend
 /security
 /server.js

File server.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.

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 Google Chrome/Windows certificates store (Chrome also saves this in Windows).

Step 6. open Dev Tools in Chrome, go to Security panel, and then click on View Certificate.

Enter image description here

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

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.

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

Choose manage certificates

Step 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.cer file certificate we just finished exporting in step 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.

Confirm security exception

Step 12. close everything, and restart Chrome. Then, when going to https://localhost:3000 you should see:

We have got to love the green

Upvotes: 190

Jos
Jos

Reputation: 420

There are more aspects to this.

You can achieve TLS (some keep saying SSL) with a certificate, self-signed or not.

To have a green bar for a self-signed certificate, you also need to become the certificate authority (CA). This aspect is missing in most resources I found on my journey to achieve the green bar in my local development setup. Becoming a CA is as easy as creating a certificate.

This resource covers the creation of both the CA certificate and a server certificate and resulted my setup in showing a green bar on localhost Chrome, Firefox and Edge: https://ram.k0a1a.net/self-signed_https_cert_after_chrome_58

Please note: in Chrome you need to add the CA certificate to your trusted authorities.

Upvotes: 2

Diego Mello
Diego Mello

Reputation: 5410

The shortest way

It was tested on macOS, but it may work similarly on other OSes.

Generate the .pem file:

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

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

Your Express.js 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:3000 in Google Chrome and you'll see that it's not secure. Yet!
  • In Developer ToolsSecurityView 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! :)

Upvotes: 157

fuma
fuma

Reputation: 5867

How to generate an SSL certificate for localhost: link

openssl genrsa -des3 -out server.key 1024

You need to enter a password here which you need to retype in the following steps:

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

When asked about "Common Name", type in: localhost

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

Upvotes: 13

Vijay Rudraraju
Vijay Rudraraju

Reputation: 189

If you're on OS X_/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

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.

Upvotes: 4

mushcraft
mushcraft

Reputation: 2244

On Windows, I made the IIS development certificate trusted by using MMC (start → Runmmc), 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 taskexport. Accept all defaults in the exporting wizard.

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

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

Resolution #2

Upvotes: 2

B T
B T

Reputation: 60975

If you're using Node.js, generate them with Node.js. This module seems to be pretty full featured:

  • pem. Create private keys and certificates with Node.js

Note that I wouldn't generate on the fly. Generate it 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.

Upvotes: 3

TroyWorks
TroyWorks

Reputation: 411

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)

Windows Vista and Windows 7

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

  1. Click Start → All ProgramsAccessories

  2. Right click Notepad and select Run as administrator

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

  4. When Notepad opens, click menu FileOpen

  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

On Mac or Linux:

  1. Open /etc/hosts with su permission
  2. Add 127.0.0.1 localdev.YOURSITE.net
  3. Save it

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.

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

2) create the certificate using that localdev.url

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

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

Upvotes: 6

user1741851
user1741851

Reputation:

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

You are going to need a .key and .crt file to add HTTPS to a Node.js Express.js server. Once you generate this, use this code to add HTTPS to the server.

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.

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 a self-signed certificate, please enlighten us.

Upvotes: 79

Bersan
Bersan

Reputation: 3487

Posting this here, as @Michael Litvin suggested, a modification needed to make the other answer work:

> openssl req  -newkey rsa:2048  -x509  -nodes  -keyout keytmp.pem  -new  -out cert.pem  -subj /CN=localhost  -reqexts SAN  -extensions SAN  -config <(cat /System/Library/OpenSSL/openssl.cnf  <(printf '[SAN]\nsubjectAltName=DNS:localhost'))  -sha256  -days 3650


> openssl rsa -in keytmp.pem -out key.pem
  1. Use key.pem for private key, cert.pem for the public certificate.

  2. Open https://localhost:PORT,

  3. Right click > Developer Tools > Security tab > View Certificate > Details > Export.

  4. Click on the saved file, add certificate to your system.

  5. Double click certificate on keychain> Trust > Always trust

Upvotes: 0

matt
matt

Reputation: 519

its often required to use https for simple development work and to save going through the rigormal of creating a new set of keys and certificates every time I want to run some code

I use the following server certificate, private key and ca cert

for .... : https://localhost , https://127.0.0.1 , https://127.0.0.2 , https://tst-server

until .. : Dec 30 09:30:07 2049

the ca certificate needs to be installed into the trusted certificate store if you want the server to be automatically trusted, bounca.org : install root certificate ( note : show all files )

a host file entry will be required for tst-server to be resolved, phoenixnap.com : How to Edit Hosts File

to check the validity of a certificate, paste the plain text part of the certificates here keycdn.com : Certificate Checker

i also created a useful npm module for quickly setting up https, npm : https-quick

      var port    = 443;
      var host    = '127.0.0.1'; 
      var key,cert,cacert;
      setup();

      //require('fs').writeFile(__dirname+'/ca-cert',ca_cert);

      var https    = require('https');
      var server   = https.createServer({key,cert});
      server.listen(port,host);

      server.on('request',(req,res)=>{
            res.writeHead(200,{'Content-Type':'text/html'});
            res.end(`<title>test ${host}:${port}</title>It Works!`);
      });
      
      
function setup(){

      key     = `
-----BEGIN RSA PRIVATE KEY-----
MIIEowIBAAKCAQEAp1/aEck7k7OGlQe373+zEYiznlk0ORrg0UeyDGsULaGyIpG+
DW/1m6hga/y5LCObKNYhU2O2CYLOunzEXgFEhLq73zQ1rWNKdF/dE1P97lAeNmJ7
qapVHgmvqRR+M5JxGHHAr3cRS06WW2H4jJD4HWVuYhuww6igP6WhVWYoPn6sgDcW
E+HLI1DVwTxkA9J/poPSSdT/VEgvH2aOwA0h1KVa9l6DrC3E/tPo8D8NPyeViSRb
/HjyI3gXr74jQvq8+4fTcftNAtyhUXUhXvlryBGKZmARB1gXAiNCuXYK08I8PmhR
PwqVq15YYto9E4QYkfCZoJaNrztbFCfDl8yiVQIDAQABAoIBABhTaQlOuvbzj6rX
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9CJCYIQm8tSMCrLD53DtoiMTuP1LDFu
5r3/rrCl5dRcb33nWz76hggtxpJo4H5DqLjoZlbajWxee5fSwqiBgWN2WNfFeui4
2DLyPhNkj/odVDub9Jxc8RoKK+D89b4/2jM955IiExkWb8MItV0E
-----END RSA PRIVATE KEY-----
`;

      cert    = `
Certificate:
    Data:
        Version: 3 (0x2)
        Serial Number: 4096 (0x1000)
    Signature Algorithm: sha256WithRSAEncryption
        Issuer: CN=tst-root-ca
        Validity
            Not Before: Aug 14 09:30:07 2022 GMT
            Not After : Dec 30 09:30:07 2049 GMT
        Subject: CN=tst-server
        Subject Public Key Info:
            Public Key Algorithm: rsaEncryption
                Public-Key: (2048 bit)
                Modulus:
                    00:a7:5f:da:11:c9:3b:93:b3:86:95:07:b7:ef:7f:
                    b3:11:88:b3:9e:59:34:39:1a:e0:d1:47:b2:0c:6b:
                    14:2d:a1:b2:22:91:be:0d:6f:f5:9b:a8:60:6b:fc:
                    b9:2c:23:9b:28:d6:21:53:63:b6:09:82:ce:ba:7c:
                    c4:5e:01:44:84:ba:bb:df:34:35:ad:63:4a:74:5f:
                    dd:13:53:fd:ee:50:1e:36:62:7b:a9:aa:55:1e:09:
                    af:a9:14:7e:33:92:71:18:71:c0:af:77:11:4b:4e:
                    96:5b:61:f8:8c:90:f8:1d:65:6e:62:1b:b0:c3:a8:
                    a0:3f:a5:a1:55:66:28:3e:7e:ac:80:37:16:13:e1:
                    cb:23:50:d5:c1:3c:64:03:d2:7f:a6:83:d2:49:d4:
                    ff:54:48:2f:1f:66:8e:c0:0d:21:d4:a5:5a:f6:5e:
                    83:ac:2d:c4:fe:d3:e8:f0:3f:0d:3f:27:95:89:24:
                    5b:fc:78:f2:23:78:17:af:be:23:42:fa:bc:fb:87:
                    d3:71:fb:4d:02:dc:a1:51:75:21:5e:f9:6b:c8:11:
                    8a:66:60:11:07:58:17:02:23:42:b9:76:0a:d3:c2:
                    3c:3e:68:51:3f:0a:95:ab:5e:58:62:da:3d:13:84:
                    18:91:f0:99:a0:96:8d:af:3b:5b:14:27:c3:97:cc:
                    a2:55
                Exponent: 65537 (0x10001)
        X509v3 extensions:
            X509v3 Basic Constraints: critical
                CA:FALSE
            X509v3 Key Usage: critical
                Digital Signature, Non Repudiation, Key Encipherment, Key Agreement
            X509v3 Extended Key Usage: critical
                TLS Web Server Authentication
            X509v3 Subject Key Identifier:
                3E:94:90:A9:2D:D7:71:A3:19:79:81:19:08:EE:CB:4A:AB:16:20:07
            X509v3 Authority Key Identifier:
                keyid:4B:0D:7A:26:6B:7A:A1:9E:EB:98:19:27:77:42:D0:BB:D0:A1:57:16
                DirName:/CN=tst-root-ca
                serial:EA:41:A9:B3:0F:FF:81:95
                
            X509v3 Subject Alternative Name:
                DNS:localhost, IP Address:127.0.0.1, IP Address:127.0.0.2, DNS:tst-server
    Signature Algorithm: sha256WithRSAEncryption
         93:ea:dc:4a:9c:3d:cb:df:bf:8a:9b:b9:22:40:21:c0:b1:77:
         20:31:d9:fc:ae:b1:41:bf:ca:58:52:aa:be:55:37:d4:f1:f4:
         4e:7b:2d:38:47:7c:63:2a:9f:36:d0:73:9c:7e:10:3b:8d:81:
         21:7e:10:d1:99:c0:4c:15:b4:79:66:4f:94:41:7f:15:72:3e:
         19:52:04:59:14:1d:a7:e2:04:36:60:7a:cc:ee:82:2a:46:82:
         7f:cc:90:ba:b0:d2:a4:eb:93:0b:0c:f6:ab:82:d0:90:36:3c:
         6c:04:74:6d:43:e9:ed:a6:3b:dd:e9:34:b7:a4:65:11:95:ba:
         ca:ef:67:7a:16:89:39:49:a8:9c:64:44:14:ba:26:8f:a6:37:
         e1:37:f4:0d:36:f8:39:cc:4e:a9:49:f6:21:33:e3:f5:b1:12:
         de:7e:66:eb:09:7c:41:b7:09:4c:d5:6a:04:65:29:13:07:d3:
         bb:13:4e:56:b2:28:f2:ba:c6:a7:ac:ba:92:68:06:40:49:dd:
         4a:43:85:f5:6b:87:85:7a:cf:3f:38:78:85:58:e7:80:fd:72:
         d0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C1jYYIJAOpBqbMP/4GVMA0GCSqGSIb3DQEBCwUAA4IBAQCD
GB8xbbozjvEij6DESLKougYHjG33lT79tegixXnh+fFwr374VTx+nEcmz8ha0cFA
z0lig/8aOJm2vlB+iGY9/chztd91QL4/xiTIi4dYZFbQXXpsSwaIaEEDJ496p+Kx
nlh4AgczG7Yxs1MPm7QiYdLpRD128x8B4gkOwe54D9yUch/PHkb5jkII7a1ctb9q
ZzrfWtPiYt7x/DT1ljIYo2m4lLdns5CHkqHlDRjyaiV4kgi7EVlpIKvjZaNNpN1a
0aKw0m5zG50jX44AtKttW/EybFj0KR9hHeaGvB9MFIz2ZiPM9OGek6NPrLr7tSjJ
KcW4i/Y+AMJCHEjy+Mj/
-----END CERTIFICATE-----
`;

}//setup

Upvotes: 0

ObiHill
ObiHill

Reputation: 11886

To follow up on answers from @Alon and @Diego above, the following should eliminate some of the manual browsers steps:

  1. Create your request config file [as ./req.cnf]:
[req]
distinguished_name = req_distinguished_name
x509_extensions = v3_req
prompt = no
[req_distinguished_name]
C = NG
ST = Lagos
L = Ikeja
O = Acme
OU = Dev 
CN = localhost
[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
  1. Create your certificate files [by running the following in your terminal]:
openssl req -x509 -nodes -days 365 -newkey rsa:2048 -keyout client-cert.key -out client-cert.pem -config req.cnf -sha256
  1. Add as trusted certificates to your Keychain:
sudo security add-trusted-cert -d -r trustRoot -k /Library/Keychains/System.keychain ./client-cert.pem

Note: Update the req.cnf according to your specific location, etc.

Note: This procedure was tested on MacOS High Sierra (10.13.6). If you're on Windows, you may need an alternative command for Step 3.

Upvotes: 1

Yogi Arif Widodo
Yogi Arif Widodo

Reputation: 679

in my case the .cert always change to default ( thats mean denied ) what ever we have change to always trusted. my device is macOS.

  1. command + space , type keychain access and open it.
  2. so we need to drag and drop into System Keychains -> System for the .cert file and double click on file -> get info -> make it change always trusted
  3. so my chrome for localhost or 127.0.0.1 the hyperlink proccess unsafe are visible , before its gone type.
openssl genrsa -out server.key 2048
openssl req -new -x509 -key server.key -out server.cert -days 365

Upvotes: 0

Deepak Singh
Deepak Singh

Reputation: 91

For windows, follow these simple steps.

  1. Open Windows PowerShell, run as administrator
  2. install Chocolatey following this hyperlink.
  3. use choco install mkcert to install mkcert.
  4. run mkcert -install will create local CA.
  5. run mkcert localhost 127.0.0.1 ::1 will create a trusted cert for localhost in the current directory.
  6. Use the generated ./localhost+2.pem and ./localhost+2-key.pem in your server as cert and key respectively. (adding key and cert varies from server to server.)
  7. Finally run your server using the setup described in various other answers (For Express server, it is given below)
    const https = require('https');
    const fs = require('fs');
    const express = require('express');

    const app = express();


    app.get('/', function(req, res){
      res.send("HELLO!");
    });

    const server = https.createServer({
        key: fs.readFileSync('./localhost+2-key.pem'), // path to localhost+2-key.pem
        cert: fs.readFileSync('./localhost+2.pem'), // path to localhost+2.pem
        requestCert: false,
        rejectUnauthorized: false,
    }, app).listen(3000, function(){
      console.log("Successfully started server on port 3000");
    });

then run your server using node server.js

  1. On your browser use https://localhost:3000 and you will see a lock in address bar.

Enjoy!!

Upvotes: 8

Brandon
Brandon

Reputation: 91

SMH, a lot of hours wasted on this due to lack of proper documentation and not everyone uses IIS... If anyone else is still stuck on this issue I hope this helps.

Solution: Trusted Self Signed SSL CERT for localhost on Windows 10

Note: If you only need the SSL cert follow the Certification Creation section

Stack: Azure Function App(Node.js), React.js - Windows 10

Certification Creation

Step 1 - Create Certificate: OpenPowershell and run the following:

New-SelfSignedCertificate -NotBefore (Get-Date) -NotAfter (Get-Date).AddYears(5) `
-Subject "CN=localhost" -KeyAlgorithm "RSA" -KeyLength 2048 `
-HashAlgorithm "SHA256" -CertStoreLocation "Cert:\CurrentUser\My" `
-FriendlyName "HTTPS Development Certificate" `
-TextExtension @("2.5.29.19={text}","2.5.29.17={text}DNS=localhost")

Step 2 - Copy Certificate: Open Certificate Manager by pressing the windows key and search for "manage user certificates". Navigate to Personal -> Certificates and copy the localhost cert to Trusted Root Certification Authorities -> Certificates

Personal -> Certificates

Trusted Root Certification Authorities -> Certificates

(Friendly Name will be HTTPS Development Certificate)

Step 3. Export Certificate right click cert -> All Tasks -> Export which will launch the Certificate Export Wizard: Certificate Export Wizard

  • Click next
  • Select Yes, export the private Key Export private key
  • Select the following format Personal Information Exchange - PKCS #12 and leave the first and last checkboxes selected. Export format
  • Select a password; enter something simple if you like ex. "1111" Enter password
  • Save file to a location you will remember ex. Desktop or Sites (you can name the file development.pfx) Save file

Step 4. Restart Chrome

Azure Function App (Server) - SSL Locally with .PFX

In this case we will run an Azure Function App with the SSL cert.

  • copy the exported development.pfx file to your azure functions project root
  • from cmd.exe run the following to start your functions app func start --useHttps --cert development.pfx --password 1111" (If you used a different password and filename don't forget to update the values in this script)
  • Update your package.json scripts to start your functions app:

React App (Client) - Run with local SSL

Install openssl locally, this will be used to convert the development.pfx to a cert.pem and server.key. Source - Convert pfx to pem file

  1. open your react app project root and create a cert folder. (project-root/cert)
  2. create a copy of the development.pfx file in the cert folder. (project-root /cert/development.pfx)
  3. open command prompt from the cert directory and run the following:
  4. convert development.pfx to cert.pem: openssl pkcs12 -in development.pfx -out cert.pem -nodes
  5. extract private key from development.pfx to key.pem: openssl pkcs12 -in development.pfx -nocerts -out key.pem
  6. remove password from the extracted private key: openssl rsa -in key.pem -out server.key
  7. update your .env.development.local file by adding the following lines:
SSL_CRT_FILE=cert.pem
SSL_KEY_FILE=server.key
  1. start your react app npm start

Upvotes: 4

mummybot
mummybot

Reputation: 2788

If you need to go a step further than @alon's detailed steps and also create a self signed ca:

https.createServer({
  key: fs.readFileSync(NODE_SSL_KEY),
  cert: fs.readFileSync(NODE_SSL_CERT),
  ca: fs.readFileSync(NODE_SSL_CA),
}, app).listen(PORT, () => {});

package.json

"setup:https": "openssl genrsa -out src/server/ssl/localhost.key 2048
&& openssl req -new -x509 -key src/server/ssl/localhost.key -out src/server/ssl/localhost.crt -config src/server/ssl/localhost.cnf
&& openssl req -new -out src/server/ssl/localhost.csr -config src/server/ssl/localhost.cnf
&& openssl x509 -req -in src/server/ssl/localhost.csr -CA src/server/ssl/localhost.crt -CAkey src/server/ssl/localhost.key -CAcreateserial -out src/server/ssl/ca.crt",

Using the localhost.cnf as described:

[req]
distinguished_name = req_distinguished_name
x509_extensions = v3_req
prompt = no
[req_distinguished_name]
C = UK
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

Upvotes: 2

som
som

Reputation: 2477

Mkcert from @FiloSottile makes this process infinitely simpler:

  1. Install mkcert, there are instructions for macOS/Windows/Linux
  2. mkcert -install to create a local CA
  3. mkcert localhost 127.0.0.1 ::1 to 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 explicitly in 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.

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

Upvotes: 35

Alphapage
Alphapage

Reputation: 919

Go to: chrome://flags/

Enable: Allow invalid certificates for resources loaded from localhost.

You don't have the green security, but you are always allowed for https://localhost in chrome.

Upvotes: 4

Related Questions