I am trying to create a web server where I can get the certificate from the client/peer as I need to read the SAN and Subject fields. The CA and localhost certificates have been generated using mkcert (I also used openssl) where it adds the CA.crt to the browser and system ca-certificate bundle.
When I start node NODE_TLS_REJECT_UNAUTHORIZED='0' node index.js it immediately gives an authorizationError: SELF_SIGNED_CERT_IN_CHAIN.
Using Chrome when I naviate to the site it reports:
This site can’t provide a secure connectionlocalhost didn’t accept your login certificate, or one may not have been provided.
Try contacting the system admin.
ERR_BAD_SSL_CLIENT_AUTH_CERT
Not sure where I'm going wrong. Any help appreciated!
const fs = require("fs");
const key = fs.readFileSync("./localhost-key.pem");
const cert = fs.readFileSync('./localhost.pem');
const express = require("express");
const app = express();
const router = express.Router();
app.get("/", (req, res, next) => {
const tlsSock = req.socket;
console.log(tlsSock.authorized)
console.log(tlsSock.authorizedError)
console.log(tlsSock.getCertificate());
res.status(200).send("Hello world!");
});
const https = require("https");
const server = https.createServer(
{
key,
cert,
requestCert: true, // Need mTLS so the peer certificate is sent.
},
app
);
var req = https
.request({
url: "https://localhost",
})
.on("error", function (err) {
console.log("err:", err);
})
.on("response", function (res) {
console.log("peerCertificate:", res.socket.getPeerCertificate());
console.log("authorized:", res.socket.authorized);
console.log("authorizationError:", res.socket.authorizationError);
});
req.end();
const port = 3000;
server.listen(port, () => {
console.log(`Server is listening on https://localhost:${port}`);
});
Related
i am trying to send an https request from my frontend (reactjs) to backend (nodejs/express).
These two both run in localhost.
Back end server code:
const app = require('./app')
const https = require('https');
const fs = require('fs');
const credentials = {
key: fs.readFileSync('key.pem'),
cert: fs.readFileSync('cert.pem')
};
//connect to the database
require('./db')
const port = 8765;
app.get('/', (req, res) => {
res.send('Now using https..');
});
var server = https.createServer(credentials, app);
//var server = https.createServer(app);
// listen for requests
server.listen(port, () => {
console.log("server starting on port : " + port)
});
front end request:
const {data: Sessions}= await axios.get("https://localhost:8765/...");
i am trying to send an https request from my frontend (reactjs) to backend (nodejs/express).
These two both run in localhost.
Back end server code:
const app = require('./app')
const https = require('https');
const fs = require('fs');
const credentials = {
key: fs.readFileSync('key.pem'),
cert: fs.readFileSync('cert.pem')
};
//connect to the database
require('./db')
const port = 8765;
app.get('/', (req, res) => {
res.send('Now using https..');
});
var server = https.createServer(credentials, app);
//var server = https.createServer(app);
// listen for requests
server.listen(port, () => {
console.log("server starting on port : " + port)
});
front end request:
const {data: Sessions}= await axios.get("https://localhost:8765/...");
doing this request from postman with the exact same parameters produces the desired result.However when i try to do this from frontend i get: GET https://localhost:8765/... net::ERR_CERT_AUTHORITY_INVALID in react chrome extention.I believe this is because i am using a self signed certificate and chrome browser can't verify it's validity.
Is there a way to temporarily disable this verification step from chrome?
If not how else can i solve this?
Not : Doing this with HTTP works fine but i need it to be HTTPS.
If your just going to run it on local host one your machine you can disable the setting at chrome://flags/#allow-insecure-localhost in browser.
This will not fix anything in production tho, only for personal use.
I am running my server on ionos hosting and executing nodejs on the default port of 80.
I don't know how to enable the HTTPS for it.
Following is my sample node js server creation code:
const Https = require('https');
const fs = require('fs');
const httpsServer = Https.createServer({
key: fs.readFileSync("private.key"),
cert: fs.readFileSync("Dev-2020-09-12-013930.cer")
}, app);
var io = require('socket.io').listen(Https);
global.SOCKET = io;
const ip = require('ip');
console.log('websocket server start.' + ' ipaddress = ' + ip.address() );
// const socket = io('http://localhost:5000');
httpsServer.listen(80, function () {
console.log('Server port: ' + port);
});
I have generated certificates and added them. On running the server it gives message of server started but does not load on browser.
Try adding these lines of code and see if you get "Hello" text in your browser.
https.get("/", (req, res) => {
res.send("Hello");
});
if that didn't work try doing it this way
httpsServer.get("/", (req, res) => {
res.send("Hello");
});
EDIT
Check out the official documentation https://nodejs.org/api/https.html
I am given to understand that if I want to use wss I need to have certification and key so I generated two
openssl req -x509 -newkey rsa:2048 -keyout key.pem -out cert.pem -days 100 -nodes
I have a code which works in Express but does not work as following :
const server = https.createServer({
cert: fs.readFileSync('/www/wwwroot/mydomain/cert/cert.pem'),
key: fs.readFileSync('/www/wwwroot/mydomain/cert/key.pem')
});
console.log(server)
const wss = new Websocket.Server({ server })
server.listen(8082)
How can I run wss in nextjs?
Seems like you might be after a two part answer:
How to set up a socket api in NextJS
How to authenticate that api with pem files
How to set up a socket api in NextJS
As usual I would direct you to the examples on the project. They are really good and have solved a lot of my questions in the past.
In this case I didn't find any examples for web-sockets, but after a bit of digging I found this sample.
https://github.com/vercel/next.js/tree/442fbfaa4d4e8205cf10c7e5d27b8f51b7a4bdc6/examples/with-socket.io
How to authenticate that api with pem files
Using the sample above and your auth logic, you should be able to do everything around the WSS server before you tell the NextJs what do do.
Your wssServer logic will define what is possible and your NextJsServer is acting like a middleman, defining which queries go where.
https://github.com/vercel/next.js/blob/442fbfaa4d4e8205cf10c7e5d27b8f51b7a4bdc6/examples/with-socket.io/server.js
// server.js
const app = require('express')()
const server = require('http').Server(app)
const io = require('socket.io')(server)
const next = require('next')
const port = parseInt(process.env.PORT, 10) || 3000
const dev = process.env.NODE_ENV !== 'production'
const nextApp = next({ dev })
const nextHandler = nextApp.getRequestHandler()
// fake DB
const messages = {
chat1: [],
chat2: [],
}
// socket.io server
io.on('connection', socket => {
socket.on('message.chat1', data => {
messages['chat1'].push(data)
socket.broadcast.emit('message.chat1', data)
})
socket.on('message.chat2', data => {
messages['chat2'].push(data)
socket.broadcast.emit('message.chat2', data)
})
})
nextApp.prepare().then(() => {
app.get('/messages/:chat', (req, res) => {
res.json(messages[req.params.chat])
})
app.get('*', (req, res) => {
return nextHandler(req, res)
})
server.listen(port, err => {
if (err) throw err
console.log(`> Ready on http://localhost:${port}`)
})
})
don't understand what's wrong with my server and code. I am passing tutorial and did everything just like in the video but still have the problem
Image
It seems like you are using https connection without handling TLS certificates passing.
Here is a code snippet to make you access your openweathermap API without configurating certificates.
const express = require('express')
const https = require('https')
const app = express()
app.get("/", function(req, res) {
const url = "<openweathermap>"
var options = require('url').parse( /**String*/ url );
options.rejectUnauthorized = false;
https.get(options, function(response) {
console.log(response);
}).on( 'error',function ( e ) {
console.log(err);
}).end();
res.send("Sever up and running");
}
app.listen(3000, function(){
console.log("Server running on port 3000";
}
I would suggest to read more on how to setup certificates for HTTPS in Node.JS,
refer this doc. for more details.
Im trying to run nodejs app to work with my php project. the problem is I think with SSL which is enabled in the server.
I have two files that I found in my root directory after SSL install: domain.com.csr and domain.com.key and I tried to combine them to connection while creating https server, but nothing worked for me.
so far I have this code:
var socket = require('socket.io');
var express = require('express');
var http = require('http');
var app = express();
var server = http.createServer(app);
var io = socket.listen(server);
app.get('/test', function(req, res) {
res.send('hello world');
console.log('visited test')
});
io.sockets.on('connection', function (client) {
console.log("New client !");
client.on('message', function (data) {
console.log('Message received ' + data.name + ":" + data.message);
io.sockets.emit('message', {name: data.name, message: data.message});
});
});
server.listen(8080, function () {
console.log('listen me on: 8080');
});
and it works well when I'm trying to visit http://ip:8080/test so it means that node server is working, but when I try to create socket connection on my view file var socket = io.connect('http://ip:8080'); it gives me error:
The page at 'https://www.domain.com/' was loaded over HTTPS, but requested an insecure XMLHttpRequest endpoint 'http://ip:8080/socket.io/?EIO=3&transport=polling&t=1446818946199-0'. This request has been blocked; the content must be served over HTTPS.
so the problem is clear enough, but how to deal with it?
also I have tried this connection:
var socket = io.connect('https://www.domain.com:8080');
but the result is 404 GET Error. How to deal with it?
Update
now the part of code I should use, but don't know how to get cert of existing SSL in the server.
var socket = require('socket.io');
var express = require('express');
var https = require('https');
var fs = require('fs');
var options = {
key: fs.readFileSync('path/to/key.pem'), // dont have
cert: fs.readFileSync('path/to/cert.cert') // dont have
};
var app = express();
var server = https.createServer(options, app);
var io = socket.listen(server);
app.get('/test', function(req, res) {
res.send('hello world');
console.log('visited test')
});
io.sockets.on('connection', function (client) {
console.log("New client !");
client.on('message', function (data) {
console.log('Message received ' + data.name + ":" + data.message);
io.sockets.emit('message', {name: data.name, message: data.message});
});
});
server.listen(443, function () {
console.log('listen me on: 443');
});
I think you need to contact your certificate authority (the organization that issued your first ssl certificate) and get a copy of the certificate (the path/to/key.pem and path/to/cert.cert) or find the existing keys somewhere on your existing server.
If you're running apache, your configuration file will have a section with values for the paths of the .cert and .pem files labeled SSLCertificateFile and SSLCertificateKeyFile, then just update the paths in your node app to point to them. You also have to make sure that your SSL certificate meets the requirements (for example, needs to be Multi-domain if your node app runs on a different domain, or a Wildcard SSL certificate to run your node app on a subdomain).
The domain.com.csr and domain.com.key files you found are the private key and certificate request used to generate your initial SSL certificate and aren't going to do anything to enable SSL on your node app.