Related
I have a node/express server running https on localhost:9002, and I want to use client certificate for a react app, running on localhost:8080 (webpack dev server). The react app is using ajax request with superagent to the https server, and I have a passport middleware to check certificate automatically.
Environment
Windows 10, Chrome Version 71.0.3578.98
Setup
Using openssl, I created a root CA. Then I generated my server certificate, and a client certificate. This is the script used (I run it with git bash, so it's UNIX style but I'm on windows):
## CREATE CERTIFICATES FOR AUTHENTICATION
#########################################
## 1. Create Root Certificate Authority #
#########################################
# Root CA private key
openssl genrsa -out ./rootCA.key 4096
# Root CA certificate to register in RootCA store on OS
openssl req -x509 -new -nodes -key ./rootCA.key -sha256 -days 3650 -out ./rootCA.pem
#################################
## 2. Create Server certificate #
#################################
# Create private key for server
openssl genrsa -out ./server.key 4096
# Create server certificate sign request (CSR) based on the private key
openssl req -new -sha256 -nodes -out ./server.csr -key ./server.key -config ./server.csr.conf
# Create server certificate linked to the previoulsy created Root CA
openssl x509 -req -in ./server.csr -CA ./rootCA.pem -CAkey ./rootCA.key -CAcreateserial -out ./server.crt -days 3650 -sha256 -extfile ./v3.ext
#################################
## 3. Create Client certificate #
#################################
# Create private key for client
openssl genrsa -out ./client.key 4096
# Create the Certificate Sign Request (CSR) file from the client private key
openssl req -new -config ./client.csr.conf -key ./client.key -out ./client.csr
# Self sign the certificate for 10 years
openssl x509 -req -days 3650 -in ./client.csr -CA ./server.crt -CAkey ./server.key -CAcreateserial -out ./client.crt
# Display the fingerprint of the newly generated fingerprint
openssl x509 -noout -fingerprint -inform pem -in ./client.crt
# Generate a PFX file for integration in browser
openssl pkcs12 -export -out ./client.pfx -inkey ./client.key -in ./client.crt -passout pass:
Here are the different configurations used:
server.csr.conf
[ req ]
default_bits = 4096
default_md = sha512
prompt = no
encrypt_key = no
distinguished_name = req_distinguished_name
# distinguished_name
[ req_distinguished_name ]
countryName = "FR"
localityName = "Lille"
organizationName = "Sopra Steria"
organizationalUnitName = "Webskillz"
commonName = "localhost"
v3.ext
authorityKeyIdentifier=keyid,issuer
basicConstraints=CA:FALSE
keyUsage = digitalSignature, nonRepudiation, keyEncipherment, dataEncipherment
subjectAltName = #alt_names
[alt_names]
DNS.1 = localhost
client.csr.conf
[ req ]
default_bits = 4096
default_md = sha512
default_keyfile = server.key
prompt = no
encrypt_key = no
distinguished_name = req_distinguished_name
# distinguished_name
[ req_distinguished_name ]
countryName = "FR"
localityName = "Lille"
organizationName = "Sopra Steria"
organizationalUnitName = "Webskillz"
commonName = "localhost"
Finally, I addedd rootCA.pem to the Trusted Root Certification Authorities using certmgr.msc, and I added the client.pfx and server.crt certificate to the Personnal store.
Issue 1
Chrome is annoyingly redirecting http://localhost:8080 to https://localhost:8080, and I don't want to systematically open chrome://net-internals/#hsts to delete the localhost key...
Issue 2
When I finally access to http://localhost:8080, I'm asked to choose the certificate I want to authenticate to https://localhost:9002 (yeay!), but I still get a 401, which is not caused by the passport cert-auth middleware (there is no log in my middleware).
Additional information
1. Almost working setup
I managed to make this client/server setup work without a root certificate, but the issue was that I got a NET::ERR_CERT_AUTHORITY_INVALID from Chrome... That's why I added a root CA, following some advice on the World Wide Web... And indeed it corrected the problem, but then I was not able to authenticate, and Chrome began to redirect automatically http to https ಠ෴ಠ
Oh by the way, CORS is allowed server side so no problems from CORS.
2. Server code
Passport auth strategy: we just check for the fingerprint in the database.
cert-auth.js
import { Strategy } from 'passport-client-cert';
export default new Strategy(async (clientCert, done) => {
console.log(clientCert); // NO LOG HERE!!
if (clientCert.fingerprint) {
try {
const user = await findByFingerprintInMyAwesomeDb({ fingerprint: clientCert.fingerprint });
return done(null, user);
} catch (err) {
return done(new Error(err));
}
}
return done(null, false);
});
bootstrap-express.js
import passport from 'passport';
import certificateStrategy from 'cert-auth';
export default (app) => {
// CORS setup, bodyparser stuff & all...
// ... //
// Using authentication based on certificate
passport.use(certificateStrategy);
app.use(passport.initialize());
app.use(passport.authenticate('client-cert', { session: false }));
// Api routes.
app.get('/api/stream',
passport.authenticate('client-cert', { session: false }),
(req, res) => {
// Some router stuff
});
};
index.js
import https from 'https';
import express from 'express';
import fs from 'fs';
import path from 'path';
import bootstrapExpress from 'bootstrap-express';
const certDir = path.join(__dirname, '..', 'cert');
const listenPromise = server => port => new Promise((resolve, reject) => {
const listener = server.listen(port, err => (err ? reject(err) : resolve(listener)));
});
const options = {
key: fs.readFileSync(path.join(certDir, 'server.key')),
cert: fs.readFileSync(path.join(certDir, 'server.crt')),
ca: fs.readFileSync(path.join(certDir, 'server.crt')),
requestCert: true,
rejectUnauthorized: false,
};
(async function main() {
try {
logger.info('Initializing server');
const app = express();
bootstrapExpress(app);
const httpsServer = https.createServer(options, app);
const httpsListener = await listenPromise(httpsServer)(9002);
logger.info(`HTTPS listening on port ${httpsListener.address().port} in ${app.get('env')} environment`);
} catch (err) {
logger.error(err);
process.exit(1);
}
}());
Conclusion
Any help is welcome :)
Regards
Okay, I did many changes so that the chain of certificate could be clearer, but the reason I was still having 401 after all my efforts was because of this configuration in my express server:
const options = {
key: fs.readFileSync(path.join(certDir, 'server.key')),
cert: fs.readFileSync(path.join(certDir, 'server.crt')),
ca: fs.readFileSync(path.join(certDir, 'server.crt')),
requestCert: true,
rejectUnauthorized: false,
};
The working configuration is the following (replacing ca by the rootCA):
const options = {
key: fs.readFileSync(path.join(certDir, 'server.key')),
cert: fs.readFileSync(path.join(certDir, 'server.crt')),
ca: fs.readFileSync(path.join(certDir, 'rootCA.pem')),
requestCert: true,
rejectUnauthorized: false,
};
This issue helped me by the way, but I only find it few minutes ago: https://github.com/nodejs/help/issues/253^
Additional Info: in order to avoid the redirection from http to https because my server was on the localhost DNS, I simply added a new DNS in C:\Windows\System32\drivers\etc\host
127.0.0.1 mysuperdns
Therefore, the common name for the server certificate must be mysuperdns.
I am messing with login form right now with node.js, I tried creating a pem key and csr using
openssl req -newkey rsa:2048 -new -nodes -keyout key.pem -out csr.pem
However I been getting errors for running node server.js
Here is my server.js
var http = require('http'),
express = require('express'),
UserServer = require('./lib/user-server');
var https = require('https');
var fs = require('fs');
var options = {
key: fs.readFileSync('./key.pem', 'utf8'),
cert: fs.readFileSync('./csr.pem', 'utf8')
};
var app = express();
app.configure(function(){
app.use(express.bodyParser());
app.use(app.router);
app.use(express.static(__dirname + '/public'));
});
var httpserver = http.createServer(app).listen('3004', '127.0.0.1');
var https_server = https.createServer(options, app).listen('3005', '127.0.0.1');
UserServer.listen(https_server);
Here is the error
crypto.js:104
if (options.cert) c.context.setCert(options.cert);
^
Error: error:0906D06C:PEM routines:PEM_read_bio:no start line
at Object.exports.createCredentials (crypto.js:104:31)
at Server (tls.js:1107:28)
at new Server (https.js:35:14)
at Object.exports.createServer (https.js:54:10)
I tried running
openssl x509 -text -inform DER -in key.pem
It gives
unable to load certificate
140735208206812:error:0D0680A8:asn1 encoding routines:ASN1_CHECK_TLEN:wrong tag:tasn_dec.c:1319:
140735208206812:error:0D07803A:asn1 encoding routines:ASN1_ITEM_EX_D2I:nested asn1 error:tasn_dec.c:381:Type=X509
I am not exactly sure what does the error mean as my encryption file is .pem file already, so any help would be much appreciated.
Thanks
You are probably using the wrong certificate file, what you need to do is generate a self signed certificate which can be done as follows
openssl req -newkey rsa:2048 -new -nodes -keyout key.pem -out csr.pem
openssl x509 -req -days 365 -in csr.pem -signkey key.pem -out server.crt
then use the server.crt
var options = {
key: fs.readFileSync('./key.pem', 'utf8'),
cert: fs.readFileSync('./server.crt', 'utf8')
};
I removed this error by write the following code
Open Terminal
openssl req -newkey rsa:2048 -new -nodes -keyout key.pem -out csr.pem
openssl x509 -req -days 365 -in csr.pem -signkey key.pem -out server.crt
Now use the server.crt and key.pem file
app.js or server.js file
var https = require('https');
var https_options = {
key: fs.readFileSync('key.pem', 'utf8'),
cert: fs.readFileSync('server.crt', 'utf8')
};
var server = https.createServer(https_options, app).listen(PORT);
console.log('HTTPS Server listening on %s:%s', HOST, PORT);
It works but the certificate is not trusted. You can view the image in image file.
For me the issues was I had the key and cert swapped.
var options = {
key: fs.readFileSync('/etc/letsencrypt/live/mysite.com/privkey.pem'),
cert: fs.readFileSync('/etc/letsencrypt/live/mysite.com/fullchain.pem'),
ca: fs.readFileSync('/etc/letsencrypt/live/mysite.com/chain.pem')
};
EDIT
More Complete Example (Maybe not completely functional)
Server.js
var fs = require('fs');
var sessionKey = 'ai_session:';
var memcachedAuth = require('memcached-auth');
var clients = {};
var users = {};
var options = {
key: fs.readFileSync('/etc/letsencrypt/live/somesite.com/privkey.pem'),
cert: fs.readFileSync('/etc/letsencrypt/live/somesite.com/fullchain.pem'),
ca: fs.readFileSync('/etc/letsencrypt/live/somesite.com/chain.pem')
};
var origins = 'https://www.somesite.com:*';
var https = require('https').createServer(options,function(req,res){
// Set CORS headers
res.setHeader('Access-Control-Allow-Origin', origins);
res.setHeader('Access-Control-Request-Method', '*');
res.setHeader('Access-Control-Allow-Methods', 'OPTIONS, GET');
res.setHeader('Access-Control-Allow-Headers', '*');
});
var io = require('socket.io')(https);
https.listen(3000);
io.sockets.on('connection', function(socket){
socket.on('auth', function(data){
var session_id = sessionKey+data.token;
memcachedAuth.is_logged_in(session_id).then( (response) => {
if(response.is_logged_in){
// user is logged in
socket.emit('is_logged_in', true);
messenger.addUser(socket);
// dynamic room
socket.on('room', function(room){
socket.join(room);
console.log('joing room '+room);
});
socket.on('message', function(data){
messenger.receive(data.message_data);
});
}else{
// Not logged in
socket.emit('is_logged_in', false);
}
}).catch( (error) => {
console.log(error);
});
});
});
var messenger = {
socket: (socket)=>{
return socket;
},
subscribe: (room)=>{
},
unsubscribe: (room)=>{
},
send: (data)=>{
},
receive: (data)=>{
console.log(data);
//connected
if (clients[data.user_name]){
console.log('user');
}
},
addUser: (socket)=>{
socket.on('add-user', function(data){
clients[data] = {
"socket": socket.id
};
console.log('Adding User:' + data);
console.log(clients);
});
},
private: (socket)=>{
// Not working yet...
socket.on('message', function(data){
console.log("Sending: " + data + " to " + data.user_name);
if (clients[data.user_name]){
io.sockets.connected[clients[data.user_name].socket].emit("response", data);
} else {
console.log("User does not exist: " + data.user_name);
}
});
},
disconnect:()=>{
//Removing the socket on disconnect
socket.on('disconnect', function() {
for(var name in clients) {
if(clients[name].socket === socket.id) {
delete clients[name];
break;
}
}
});
}
}
I have created a repo on github including a more complete version of the above code if anyone is interested: https://github.com/snowballrandom/Memcached-Auth
Was facing the same problem In my case I changed the option parameter of cert to pfx & removed utf8 encoding.
before:
var options = {
hostname : 'localhost',
path : '/',
method : 'POST',
cert: fs.readFileSync(testCert, 'utf8'),
passphrase:passphrase,
agent:false,
rejectUnauthorized:false
};
after:
var options = {
hostname : 'localhost',
path : '/',
method : 'POST',
pfx: fs.readFileSync(testCert),
passphrase:passphrase,
agent:false,
rejectUnauthorized:false
};
I actually just had this same error message.
The problem was I had key and cert files swapped in the configuration object.
For me, after trying all above solutions it ended up being a problem related to encoding. Concisely, my key was encoded using 'UTF-8 with BOM'. It should be UTF-8 instead.
To fix it, at least using VS Code follow this steps:
Open the file and click on the encoding button at the status bar (at the bottom) and select 'Save with encoding'.
Select UTF-8.
Then try using the certificate again.
I suppose you can use other editors that support saving with the proper encoding.
Source: error:0906d06c:pem routines:pem_read_bio:no start line, when importing godaddy SSL certificate
P.D I did not need to set the encoding to utf-8 option when loading the file using the fs.readFileSync function.
Hope this helps somebody!
I faced with the problem like this.
The problem was that I added the public key without '-----BEGIN PUBLIC KEY-----' at the beginning and without '-----END PUBLIC KEY-----'.
So it causes the error.
Initially, my public key was like this:
-----BEGIN PUBLIC KEY-----
WnsbGUXbb0GbJSCwCBAhrzT0s2KMRyqqS7QBiIG7t3H2Qtmde6UoUIcTTPJgv71
......
oNLcaK2wKKyRdcROK7ZTSCSMsJpAFOY
-----END PUBLIC KEY-----
But I used just this part:
WnsbGUXb+b0GbJSCwCBAhrzT0s2KMRyqqS7QBiIG7t3H2Qtmde6UoUIcTTPJgv71
......
oNLcaK2w+KKyRdcROK7ZTSCSMsJpAFOY
If you are using windows, you should make sure that the certificate file csr.pem and key.pem don't have unix-style line endings. Openssl will generate the key files with unix style line endings. You can convert these files to dos format using a utility like unix2dos or a text editor like notepad++
I guess this is because your nodejs cert has expired. Type this line : npm set registry http://registry.npmjs.org/ and after that try again with npm install . This actually solved my problem.
For me, the solution was to replace \\n (getting formatted into the key in a weird way) in place of \n
Replace your
key: <private or public key>
with
key: (<private or public key>).replace(new RegExp("\\\\n", "\g"), "\n")
If you log the
var options = {
key: fs.readFileSync('./key.pem', 'utf8'),
cert: fs.readFileSync('./csr.pem', 'utf8')
};
You might notice there are invalid characters due to improper encoding.
Corrupted cert and/or key files
For me it was just corrupted files. I copied the contents from GitHub PullRequest webpage and I guess I added an extra space somewhere or whatever... once I grabbed the raw thing and replaced the file, it worked.
Generate the private key and server certificate with specific expiry date or with infinite(XXX) expiry time and self sign it.
$ openssl req -x509 -sha256 -newkey rsa:2048 -keyout key.pem -out cert.pem -days XXX
$ Enter a private key passphrase...`
Then it will work!
Following this guide https://git.coolaj86.com/coolaj86/ssl-root-cas.js/src/branch/master/Painless-Self-Signed-Certificates-in-node.js.md, I've created a Root CA and Signed Certificate with the following script:
make-certs.sh
#!/bin/bash
FQDN=`hostname`
# make directories to work from
rm -rf certs
mkdir -p certs/{server,client,ca,tmp}
# Create your very own Root Certificate Authority
openssl genrsa \
-out certs/ca/my-root-ca.key.pem \
2048
# Self-sign your Root Certificate Authority
# Since this is private, the details can be as bogus as you like
openssl req \
-x509 \
-new \
-nodes \
-key certs/ca/my-root-ca.key.pem \
-days 1024 \
-out certs/ca/my-root-ca.crt.pem \
-subj "/C=US/ST=Utah/L=Provo/O=${FQDN}/CN=${FQDN}"
# Create a Device Certificate for each domain,
# such as example.com, *.example.com, awesome.example.com
# NOTE: You MUST match CN to the domain name or ip address you want to use
openssl genrsa \
-out certs/server/privkey.pem \
2048
# Create a request from your Device, which your Root CA will sign
openssl req -new \
-key certs/server/privkey.pem \
-out certs/tmp/csr.pem \
-subj "/C=US/ST=Utah/L=Provo/O=${FQDN}/CN=${FQDN}"
# Sign the request from Device with your Root CA
# -CAserial certs/ca/my-root-ca.srl
openssl x509 \
-req -in certs/tmp/csr.pem \
-CA certs/ca/my-root-ca.crt.pem \
-CAkey certs/ca/my-root-ca.key.pem \
-CAcreateserial \
-out certs/server/cert.pem \
-days 500
# Create a public key, for funzies
# see https://gist.github.com/coolaj86/f6f36efce2821dfb046d
openssl rsa \
-in certs/server/privkey.pem \
-pubout -out certs/client/pubkey.pem
# Put things in their proper place
rsync -a certs/ca/my-root-ca.crt.pem certs/server/chain.pem
rsync -a certs/ca/my-root-ca.crt.pem certs/client/chain.pem
cat certs/server/cert.pem certs/server/chain.pem > certs/server/fullchain.pem
I then setup my package.json with the following:
{
"name": "api-server",
"version": "1.0.0",
"description": "API Server",
"main": "api-server.js",
"dependencies": {
"body-parser": "^1.15.2",
"express": "^4.14.0"
}
}
Ran the npm install and then created my api-server.js like this:
// Load libraries
var https = require('https'),
fs = require('fs'),
express = require('express'),
app = express(),
bodyParser = require('body-parser');
// Server setting
var port = process.env.PORT || 8080;
// Register body-parser
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
// Configure router
var router = express.Router();
app.use('/api/v1', router);
// Register routes
router.get('/', function(req, res) {
res.json({ success: true });
});
// Create & run https api server
var secureServer = https.createServer({
key: fs.readFileSync('./certs/server/privkey.pem'),
cert: fs.readFileSync('./certs/server/fullchain.pem'),
requestCert: true,
rejectUnauthorized: false
}, app).listen(port, function() {
console.log('API Server Started On Port %d', port);
});
Finally, I started the app using node api-server.js and visited https://<my-ip>:8080/ in chrome.
I got the following error:
This site can’t be reached
192.168.0.21 refused to connect.
Looking on the console log of server, I saw the following:
Any ideas what I might be doing wrong here?
I have found a way to solve/simply this.
make-certs.sh
#!/bin/bash
FQDN=`hostname`
rm server.key server.crt
openssl genrsa -out server.key 2048
openssl req -nodes -newkey rsa:2048 -keyout server.key -out server.csr -subj "/C=GB/ST=Street/L=City/O=Organisation/OU=Authority/CN=${FQDN}"
openssl x509 -req -days 1024 -in server.csr -signkey server.key -out server.crt
rm server.csr
api-server.js
// Import libraries
var express = require('express');
var server = express();
var bodyParser = require('body-parser')
var https = require('https');
var fs = require('fs');
// Server setting
var port = process.env.PORT || 8080;
// Register body-parser
server.use(bodyParser.json());
server.use(bodyParser.urlencoded({ extended: true }));
// Configure router
var router = express.Router();
server.use('/api/v1', router);
// Create https server & run
https.createServer({
key: fs.readFileSync('server.key'),
cert: fs.readFileSync('server.crt')
}, server).listen(port, function() {
console.log('API Server Started On Port %d', port);
});
// Register routes
router.get('/', function(req, res) {
res.json({ success: true });
});
This now works.
I am messing with login form right now with node.js, I tried creating a pem key and csr using
openssl req -newkey rsa:2048 -new -nodes -keyout key.pem -out csr.pem
However I been getting errors for running node server.js
Here is my server.js
var http = require('http'),
express = require('express'),
UserServer = require('./lib/user-server');
var https = require('https');
var fs = require('fs');
var options = {
key: fs.readFileSync('./key.pem', 'utf8'),
cert: fs.readFileSync('./csr.pem', 'utf8')
};
var app = express();
app.configure(function(){
app.use(express.bodyParser());
app.use(app.router);
app.use(express.static(__dirname + '/public'));
});
var httpserver = http.createServer(app).listen('3004', '127.0.0.1');
var https_server = https.createServer(options, app).listen('3005', '127.0.0.1');
UserServer.listen(https_server);
Here is the error
crypto.js:104
if (options.cert) c.context.setCert(options.cert);
^
Error: error:0906D06C:PEM routines:PEM_read_bio:no start line
at Object.exports.createCredentials (crypto.js:104:31)
at Server (tls.js:1107:28)
at new Server (https.js:35:14)
at Object.exports.createServer (https.js:54:10)
I tried running
openssl x509 -text -inform DER -in key.pem
It gives
unable to load certificate
140735208206812:error:0D0680A8:asn1 encoding routines:ASN1_CHECK_TLEN:wrong tag:tasn_dec.c:1319:
140735208206812:error:0D07803A:asn1 encoding routines:ASN1_ITEM_EX_D2I:nested asn1 error:tasn_dec.c:381:Type=X509
I am not exactly sure what does the error mean as my encryption file is .pem file already, so any help would be much appreciated.
Thanks
You are probably using the wrong certificate file, what you need to do is generate a self signed certificate which can be done as follows
openssl req -newkey rsa:2048 -new -nodes -keyout key.pem -out csr.pem
openssl x509 -req -days 365 -in csr.pem -signkey key.pem -out server.crt
then use the server.crt
var options = {
key: fs.readFileSync('./key.pem', 'utf8'),
cert: fs.readFileSync('./server.crt', 'utf8')
};
I removed this error by write the following code
Open Terminal
openssl req -newkey rsa:2048 -new -nodes -keyout key.pem -out csr.pem
openssl x509 -req -days 365 -in csr.pem -signkey key.pem -out server.crt
Now use the server.crt and key.pem file
app.js or server.js file
var https = require('https');
var https_options = {
key: fs.readFileSync('key.pem', 'utf8'),
cert: fs.readFileSync('server.crt', 'utf8')
};
var server = https.createServer(https_options, app).listen(PORT);
console.log('HTTPS Server listening on %s:%s', HOST, PORT);
It works but the certificate is not trusted. You can view the image in image file.
For me the issues was I had the key and cert swapped.
var options = {
key: fs.readFileSync('/etc/letsencrypt/live/mysite.com/privkey.pem'),
cert: fs.readFileSync('/etc/letsencrypt/live/mysite.com/fullchain.pem'),
ca: fs.readFileSync('/etc/letsencrypt/live/mysite.com/chain.pem')
};
EDIT
More Complete Example (Maybe not completely functional)
Server.js
var fs = require('fs');
var sessionKey = 'ai_session:';
var memcachedAuth = require('memcached-auth');
var clients = {};
var users = {};
var options = {
key: fs.readFileSync('/etc/letsencrypt/live/somesite.com/privkey.pem'),
cert: fs.readFileSync('/etc/letsencrypt/live/somesite.com/fullchain.pem'),
ca: fs.readFileSync('/etc/letsencrypt/live/somesite.com/chain.pem')
};
var origins = 'https://www.somesite.com:*';
var https = require('https').createServer(options,function(req,res){
// Set CORS headers
res.setHeader('Access-Control-Allow-Origin', origins);
res.setHeader('Access-Control-Request-Method', '*');
res.setHeader('Access-Control-Allow-Methods', 'OPTIONS, GET');
res.setHeader('Access-Control-Allow-Headers', '*');
});
var io = require('socket.io')(https);
https.listen(3000);
io.sockets.on('connection', function(socket){
socket.on('auth', function(data){
var session_id = sessionKey+data.token;
memcachedAuth.is_logged_in(session_id).then( (response) => {
if(response.is_logged_in){
// user is logged in
socket.emit('is_logged_in', true);
messenger.addUser(socket);
// dynamic room
socket.on('room', function(room){
socket.join(room);
console.log('joing room '+room);
});
socket.on('message', function(data){
messenger.receive(data.message_data);
});
}else{
// Not logged in
socket.emit('is_logged_in', false);
}
}).catch( (error) => {
console.log(error);
});
});
});
var messenger = {
socket: (socket)=>{
return socket;
},
subscribe: (room)=>{
},
unsubscribe: (room)=>{
},
send: (data)=>{
},
receive: (data)=>{
console.log(data);
//connected
if (clients[data.user_name]){
console.log('user');
}
},
addUser: (socket)=>{
socket.on('add-user', function(data){
clients[data] = {
"socket": socket.id
};
console.log('Adding User:' + data);
console.log(clients);
});
},
private: (socket)=>{
// Not working yet...
socket.on('message', function(data){
console.log("Sending: " + data + " to " + data.user_name);
if (clients[data.user_name]){
io.sockets.connected[clients[data.user_name].socket].emit("response", data);
} else {
console.log("User does not exist: " + data.user_name);
}
});
},
disconnect:()=>{
//Removing the socket on disconnect
socket.on('disconnect', function() {
for(var name in clients) {
if(clients[name].socket === socket.id) {
delete clients[name];
break;
}
}
});
}
}
I have created a repo on github including a more complete version of the above code if anyone is interested: https://github.com/snowballrandom/Memcached-Auth
Was facing the same problem In my case I changed the option parameter of cert to pfx & removed utf8 encoding.
before:
var options = {
hostname : 'localhost',
path : '/',
method : 'POST',
cert: fs.readFileSync(testCert, 'utf8'),
passphrase:passphrase,
agent:false,
rejectUnauthorized:false
};
after:
var options = {
hostname : 'localhost',
path : '/',
method : 'POST',
pfx: fs.readFileSync(testCert),
passphrase:passphrase,
agent:false,
rejectUnauthorized:false
};
I actually just had this same error message.
The problem was I had key and cert files swapped in the configuration object.
For me, after trying all above solutions it ended up being a problem related to encoding. Concisely, my key was encoded using 'UTF-8 with BOM'. It should be UTF-8 instead.
To fix it, at least using VS Code follow this steps:
Open the file and click on the encoding button at the status bar (at the bottom) and select 'Save with encoding'.
Select UTF-8.
Then try using the certificate again.
I suppose you can use other editors that support saving with the proper encoding.
Source: error:0906d06c:pem routines:pem_read_bio:no start line, when importing godaddy SSL certificate
P.D I did not need to set the encoding to utf-8 option when loading the file using the fs.readFileSync function.
Hope this helps somebody!
I faced with the problem like this.
The problem was that I added the public key without '-----BEGIN PUBLIC KEY-----' at the beginning and without '-----END PUBLIC KEY-----'.
So it causes the error.
Initially, my public key was like this:
-----BEGIN PUBLIC KEY-----
WnsbGUXbb0GbJSCwCBAhrzT0s2KMRyqqS7QBiIG7t3H2Qtmde6UoUIcTTPJgv71
......
oNLcaK2wKKyRdcROK7ZTSCSMsJpAFOY
-----END PUBLIC KEY-----
But I used just this part:
WnsbGUXb+b0GbJSCwCBAhrzT0s2KMRyqqS7QBiIG7t3H2Qtmde6UoUIcTTPJgv71
......
oNLcaK2w+KKyRdcROK7ZTSCSMsJpAFOY
If you are using windows, you should make sure that the certificate file csr.pem and key.pem don't have unix-style line endings. Openssl will generate the key files with unix style line endings. You can convert these files to dos format using a utility like unix2dos or a text editor like notepad++
I guess this is because your nodejs cert has expired. Type this line : npm set registry http://registry.npmjs.org/ and after that try again with npm install . This actually solved my problem.
For me, the solution was to replace \\n (getting formatted into the key in a weird way) in place of \n
Replace your
key: <private or public key>
with
key: (<private or public key>).replace(new RegExp("\\\\n", "\g"), "\n")
If you log the
var options = {
key: fs.readFileSync('./key.pem', 'utf8'),
cert: fs.readFileSync('./csr.pem', 'utf8')
};
You might notice there are invalid characters due to improper encoding.
Corrupted cert and/or key files
For me it was just corrupted files. I copied the contents from GitHub PullRequest webpage and I guess I added an extra space somewhere or whatever... once I grabbed the raw thing and replaced the file, it worked.
Generate the private key and server certificate with specific expiry date or with infinite(XXX) expiry time and self sign it.
$ openssl req -x509 -sha256 -newkey rsa:2048 -keyout key.pem -out cert.pem -days XXX
$ Enter a private key passphrase...`
Then it will work!
I am trying to use the https module in Node.js.
Here's the code:
var options = {
key : <key comes here>,
cert : <key comes here>
};
https.createServer(options, app).listen(app.get('port'));
You can use OpenSSL,
A private key is created like this
openssl genrsa -out ryans-key.pem 1024
The first step to getting a certificate is to create a "Certificate Signing Request" (CSR) file. This is done with:
openssl req -new -key ryans-key.pem -out ryans-csr.pem
To create a self-signed certificate with the CSR, do this:
openssl x509 -req -in ryans-csr.pem -signkey ryans-key.pem -out ryans-cert.pem
To create .pfx or .p12, do this:
openssl pkcs12 -export -in agent5-cert.pem -inkey agent5-key.pem \
-certfile ca-cert.pem -out agent5.pfx
Here is a simple example echo server
var tls = require('tls');
var fs = require('fs');
var options = {
key: fs.readFileSync('server-key.pem'),
cert: fs.readFileSync('server-cert.pem'),
// This is necessary only if using the client certificate authentication.
requestCert: true,
// This is necessary only if the client uses the self-signed certificate.
ca: [ fs.readFileSync('client-cert.pem') ]
};
var server = tls.createServer(options, function(cleartextStream) {
console.log('server connected',
cleartextStream.authorized ? 'authorized' : 'unauthorized');
cleartextStream.write("welcome!\n");
cleartextStream.setEncoding('utf8');
cleartextStream.pipe(cleartextStream);
});
server.listen(8000, function() {
console.log('server bound');
});
you can refer to http://nodejs.org/api/tls.html for more info,
Regards
Follow the openssl instructions found at the Node.js website.