Hi, I’m new to the site.
I am creating an application with Node.js and I have a local test server in the windows HOSTS, by “localhost”
In the application there is the possibility to log in from facebook, but I can not do it, because being in tests and on the local server the url is http: //
and not https: // that facebook requires me to be able to log in to my application through its platform.
Is there any way I can get that?
They told me that it hires SSL, but since I install that on my HOST
Thank you.
And excuse the bad spelling and syntax of the question, I must make use of the translator:
So you need HTTPS.
You came to the right place for that.
Start here: https://certbot.eff.org/all-instructions/
If you run into any problems or have any questions, then post those here.
Most OAuth2 providers will let you use http://127.0.0.1
but not http://localhost
(though I’m not sure about Facebook specifically). The reason is that localhost
can be redirected to other machines via the HOSTS file but 127.0.0.1
is always restricted to the local machine.
You seem to be actually taking advantage of the ability to redirect localhost, so you may not be able to use 127.0.0.1
.
But for this use case, you don’t require a publicly trusted certificate so you could also use this procedure:
Thanks for the documentation. Tomorrow I study it and tell it how it was.
Hello again.
I was studying the documentation that I proposed but I can not understand how I should do to make it pass through https.
My windows hosts file does not configure it in the following way, with which my application runs:
127.0.0.1 localhost
127.0.0.1 michaelgram.test
I do not understand if it is this file that I must configure and how to do http: https:
Maybe the best way is with the file “openssl”, but I do not know where I should place that file, and if it should be exactly the same as the one shown in archivo openssl
If you gave me more ideas or places to study, I would be very grateful, because they are already 4 days trying to get this.
Thank you.
What web server are you using? IIS?
The server is created with Express and I have it in localhost. he believes it to do the tests. The server.js configuration is as follows:
let express = require('express');
let aws = require(‘aws-sdk’);
let multer = require(‘multer’);
let multerS3 = require(‘multer-s3’);
let ext = require(‘file-extension’);
let cookieParser = require(‘cookie-parser’);
let bodyParser = require(‘body-parser’);
let expressSession = require(‘express-session’);
let passport = require(‘passport’);
let michaelgram = require(‘michaelgram-client’);
let auth = require(’./auth’)
let config = require(’./config’);
let port = process.env.PORT || 5050;
let client = michaelgram.createClient(config.client);
let s3 = new aws.S3({
accessKeyId: config.aws.accessKey,
secretAccessKey: config.aws.secretKey
});
let storage = multerS3({
s3: s3,
bucket: ‘michaelgram’,
acl: ‘public-read’,
metadata: function (req, file, cb) {
cb(null, { fieldName: file.fieldname })
},
key: function (req, file, cb) {
cb(null, +Date.now() + ‘.’ + ext(file.originalname))
}
});
let upload = multer({ storage: storage }).single(‘picture’);
let app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(expressSession({
secret: config.secret,
resave: false,
saveUninitialized: false
}))
app.use(passport.initialize())
app.use(passport.session())
app.set(‘view engine’, ‘pug’);
app.use(express.static(‘public’));
passport.use(auth.localStrategy);
passport.use(auth.facebookStrategy);
passport.deserializeUser(auth.deserializeUser);
passport.serializeUser(auth.serializeUser);
app.get(’/’, function (req, res) {
res.render(‘index’, { title: ‘Michaelgram’ });
})
app.get(’/signup’, function (req, res) {
res.render(‘index’, { title: ‘Michaelgram - Signup’ });
})
app.post(’/signup’, function (req, res) {
let user = req.body;
client.saveUser(user, function (err, usr) {
if (err) return res.status(500).send(err.message)
debugger
res.redirect(’/signin’);
});
});
app.get(’/signin’, function (req, res) {
res.render(‘index’, { title: ‘Michaelgram - Signin’ });
})
app.post(’/login’, passport.authenticate(‘local’, {
successRedirect: ‘/’,
failureRedirect: ‘/signin’
}));
app.get(’/logout’, function (req, res) {
req.logout()
res.redirect(’/’)
});
app.get(’/auth/facebook’, passport.authenticate(‘facebook’, { scope: ‘email’ }));
app.get(’/auth/facebook/callback’, passport.authenticate(‘facebook’, {
successRedirect: ‘/’,
failureRedirect: ‘/signin’
}));
function ensureAuth(req, res, next) {
if (req.isAuthenticated()) {
return next()
}
res.status(401).send({ error: ‘not authenticated’ })
}
app.get(’/whoami’, function (req, res) {
if (req.isAuthenticated()) {
return res.json(req.user)
}
res.json({ auth: false })
})
app.get(’/api/pictures’, function (req, res, next) {
client.listPictures(function (err, pictures) {
if (err) return res.send([]);
res.send(pictures)
})
})
app.post(’/api/pictures’, ensureAuth, function (req, res) {
upload(req, res, function (err) {
if (err) {
return res.status(500).send(Error uploading file: ${err.message}
)
}
let user = req.user
let token = req.user.token
let username = req.user.username
let src = req.file.location
client.savePicture({
src: src,
userId: username,
user: {
username: username,
avatar: user.avatar,
name: user.name
}
}, token, function (err, img) {
if (err) {
return res.status(500).send(err.message)
}
res.send(`File uploaded: ${req.file.location}`);
})
})
})
app.get(’/api/user/:username’, (req, res) => {
var username = req.params.username;
client.getUser(username, function (err, user) {
if (err) return res.status(404).send({ error: 'user not found '})
res.send(user)
})
})
app.get(’/:username’, function (req, res) {
res.render(‘index’, { title: Michaelgram - ${req.params.username}
});
})
app.get(’/:username/:id’, function (req, res) {
res.render(‘index’, { title: Michaelgram - ${req.params.username}
});
})
app.listen(port, function (err) {
if (err) return console.log(‘Hubo un error’), process.exit(1);
console.log(‘Michaelgram escuchando en el puerto 5050’);
})
¿Es hablante de Español? ¿Quiere continuar en Español? Hay algunas cosas en la traducción que no tienen tanto sentido.
Si, soy español, y hago uso del traductor para poder comunicarme.
Lo primero perdón por la demora al contestar, anoche era muy tarde y hasta ahora empecé a trabajar.
La aplicacion que estoy creando esta enteramente construida con javascript, con node.js.
El servidor creado es express, y la aplicación tiene login con g¡facebook, pero claro, como bloquearon las URL http, me encuentro bloqueado, sin poder continuar. He revisado varias cosas, su aporte es interesante, pero no termino de entender cómo configurarlo mi servidor, parece que el archivo OPENSSH parece buena opcion, pero como digo, después de cuatro horas revisando una y otra vez la documentación que me ofreció, soy incapaz de conseguirlo.
Gracias por el apoyo, buscare documentación respecto a Express a ver si es posible el login en facebook.
Gracias.
Me hablaron de que Let’s Encrypt no tiene soporte para Node.js, que quiza por medio de Certbot, podría legar a conseguirlo, pero estoy empezando con node.js y javascript y no encuentro de configurar mi archivo del server.js
Guiate a ver como se puede entroducir “SSL” en el systema express.
Gracias, voy a estudiar todo lo que ofreció, para tratar de ponerlo en mi código. Estoy empezando con node.js y javascript, por lo que tardare en mostrar los resultados. Cuando llegue a conseguirlo, lo mostraré, por si pudiera ayudar a otro con el mismo problema.
Gracias, muchas gracias.
Hola, he seguido los pasos del ejemplo que me mostró, y no lo consigo. Instale OpenSSL y trato de sacar loas llaves como en el ejemplo que es parecido al que usted me enseño https://serverfault.com/questions/842401/install-ssl-certificate-on-apache-windows-server-2012-r2/842443#842443 pero me da: permiso denegado, por lo que al correr npm start, no me deja.
¿Has logrado crear un certificado usando OpenSSL?
Deberías de tener dos archivos.
Un archivo con la llave privada y un archivo de certificado público.
Si no, puedes usar esto para crear los dos:
openssl req -new -x509 -sha256 -newkey rsa:2048 -nodes -keyout privado.key -days 3650 -out publico.cert
La unica respuesta neccesaria es “Common Name”. Use el nombre completo del servidor.
Ok, intentare probar. estuve intentando con la ayuda de un compañero, pero cometí varios errores. Seguiré probando y le comento como me fue. El me propuso varios comandos com los de usted.
Hoy se hizo muy tarde, aqui son las 0:25 AM y a las 06:00 debo salir de viaje y estoy algo frustrado por que mañana seguire probando. Gracias de nuevo, en cuanto pruebe le comento
Hola de nuevo.
Perdon por la demo al responder.
Cree los archivos con el comando que me mostro.
LOs lleve al directorio del proyecto en una carpeta llamada “unix”
Hice referencia a la carpeta desde el archivo server.js de la siguiente manera:
var options = require(’./unix’)
Y puse el siguiente codigo en server.js:
var options = {
key: fs.readFileSync('./unix/private.key'),
cert: fs.readFileSync('./unix/publico.cert')
};
http.createServer(app).listen(80);
https.createServer(options, app).listen(443);
app.listen(port, function (err) {
if (err) return console.log('Hubo un error'), process.exit(1);
console.log('Michaelgram escuchando en el puerto 5050');
})```
Pero al correr npm start y levantar el servidor me da el siguiente error:
[1] module.js:549
[1] throw err;
[1] ^
[1]
[1] Error: Cannot find module './unix'
[1] at Function.Module._resolveFilename (module.js:547:15)
[1] at Function.Module._load (module.js:474:25)
[1] at Module.require (module.js:596:17)
[1] at require (internal/module.js:11:18)
[1] at Object.<anonymous> (C:\Users\victor\CURSOS\JAVASCRIPT-NODE\PROYECTO-MICHAELGRAM\michaelgram\server.js:1456:15)
[1] at Module._compile (module.js:652:30)
[1] at Object.Module._extensions..js (module.js:663:10)
[1] at Module.load (module.js:565:32)
[1] at tryModuleLoad (module.js:505:12)
[1] at Function.Module._load (module.js:497:3)
[1] at Function.Module.runMain (module.js:693:10)
[1] at startup (bootstrap_node.js:188:16)
[1] at bootstrap_node.js:609:3
¿ Que estare haciendo mal ahora...?
Quizá deba poner los archivos creados de otro modo, pues no deberían estar en el directorio del proyecto por seguridad...
Si fuera tan amable de dar alguna idea de como hacer esto, son ya seis dis¡as los que llevo con este problema.
No se si tambien debo modificar el archivo "hosts", la verdad cuantas mas cosas encuentro del tema, mas se me esta complicando...........
Gracias
Pero "require" en Javascript quiere decir "cargar el argumento como código Javascript" (por ejemplo con una biblioteca). Es lo que intentaba hacer aquí?
No es "require" en el sentido de "verificar que el archivo o carpeta existe".
No, en esa carpeta meti los archivos creados con openssl, las llaves.
Y no se si esa la manera correcta de llamar a las llaves.
Tengo otro archivo en la raiz del proyecto llamado config.js ,donde guardo las claves de facebook y aws y le llamo desde la misma manera y funciona.
Pero claro, como usted dice, tiene script:
const config = {
aws: {
accessKey: process.env.AWS_ACCESS_KEY,
secretKey: process.env.AWS_SECRET_KEY
}
}
module.exports = config;
Pero claro, estos son archivos pem y cert, por eso no me funciona.
El tema es que he visto infinitos tutoriales y documentación, y sigo sin ser capaz de hacerlo funcionar.
Gracias por el interes.
¿ Como debo hacer referencia a esa carpeta donde tengo las llaves de openssl… ?
¿Qué pasa si no pone
?
¿Es solo que el programa no puede encontrar los archivos (la llave y el certificado)?
Me da el siguiente error:
[1] fs.js:646
[1] return binding.open(pathModule._makeLong(path), stringToFlags(flags), mode);
[1] ^
[1]
[1] Error: ENOENT: no such file or directory, open 'C:\Users\victor\CURSOS\JAVASCRIPT-NODE\PROYECTO-MICHAELGRAM\michaelgram\unix\private.key'
[1] at Object.fs.openSync (fs.js:646:18)
[1] at Object.fs.readFileSync (fs.js:551:33)
[1] at Object.<anonymous> (C:\Users\victor\CURSOS\JAVASCRIPT-NODE\PROYECTO-MICHAELGRAM\michaelgram\server.js:1612:11)
[1] at Module._compile (module.js:652:30)
[1] at Object.Module._extensions..js (module.js:663:10)
[1] at Module.load (module.js:565:32)
[1] at tryModuleLoad (module.js:505:12)
[1] at Function.Module._load (module.js:497:3)
[1] at Function.Module.runMain (module.js:693:10)
[1] at startup (bootstrap_node.js:188:16)
[1] at bootstrap_node.js:609:3```
Dice que no existe el archivo