I'm trying to do google authentication in my website, where the user gets authenticated on a page. After authentication, it generates a code which contains access_token and refresh_token, and I want to send it to my Node server.
I know Xhttp is a way but I want to avoid that.
So I tried using handle bars. But they only work for html right?
Is there anyway I could use something like helpers to send my code to the server?
I tried to get around some posts like:
How can I share code between Node.js and the browser? (which is quite old, Node must've evolved till then right ?)
Sending data from javascript/html page to Express NodeJS server (I didn't understand this one honestly)
I'm new to Node.js so any guesses or any reference to the docs?
One standard way is setting access token and refresh token on Cookie, so it will be sent with every http request to the backend and can be extracted on server side (node), for example if you use express:
var express = require('express');
var cookieParser = require('cookie-parser');
var app = express();
app.use(cookieParser());
this will set req.cookies with an object keyed by the cookie names.
Another option is to use http Authorization header to send the tokens.
Related
I am making a chat program.
I am using an Nginx server and NodeJS.
I have setup a websocket via ssl and that works fine.
I have decided to use cookies for authentication.
There are two functions which are crucial:
mconnection.prototype.make_server_https=function(){
console.log('Make server https');
var cthis=this;
var server_https=modules.https.createServer({
key: this.ssl_key,
cert:this.ssl_cert,
ca:this.ssl_ca
},(request,response)=>{
console.log('### CreateServer ###');
console.log('CreateServer, Request:');
console.log(request);
console.log('CreateServer, Response:');
console.log(response);
console.log('######');
and
mconnection.prototype.make_server_websocket=function(){
var server_websocket=new modules.ws.Server({server:this.server_https});
var cookie = require("cookie");
var cthis=this;
//whenever a new client connects with the server.
server_websocket.on('connection', function(client_socket, request){
console.log('### On Connection ###');
console.log('OnConnection, Client Socket:');
console.log(client_socket);
console.log('OnConnection, Request:');
console.log(request);
console.log('######');
If I do state the port number in the client url,function make_server_https gets run and inside there i can access the cookie and set it via the response object.
but in the original url,function make_server_websocket gets run, and there i have access to the client_socket on the server. But there it seems i dont have access to the cookies.
I need to client_websocket to start the connection with this given client. And I need to tie it somehow with the cookies login information.
But i never have both at the same time so i dont get how i could connect them to make the login happen.
I am probably misunderstanding something, any help in the right direction would really be appreciated.
you have to serve you index page from node server using GET then when the request reaches backend you will have response object which can then be used to SET-COOKIE if not set from backend.
And after GET request is complete COOKIE will be added in browser, when next request is made for websocket connection COOKIE will be added to the request in REQUEST HEADERS by the browser which will be available in backend through request object.
And if you decide to use it in login system then you can SET-COOKIE on successfull login.
i got it. its an event called on headers, not on connection. and there i can just push onto the headers.
I am inheriting a backend Express API and a front end React app.
Currently I am using cookie-parser in my POST /login API like so:
res.cookie('something', 'abc123', {
maxAge: COOKIE_MAX_AGE
});
on my front end app, there is a function for checking if an auth token exists:
export function isAuthCookiePresent() {
console.log('ALL COOKIES:', cookies.get());
return (
cookies.get(AUTH_COOKIE_NAME) && cookies.get(AUTH_COOKIE_NAME) !== null
);
}
And as expected I see { something: 'abc123' } in my console logs.
However, when I try logging in this using autodeployed branches in Vercel (https://vercel.com/), the cookie is missing.
I was under the impression that cookies were supposed to be set on the front end? But in the code the cookie is being set on the backend. And I don't see anything in the code that passes it to the front end. I thought I would find something on the front end like that would have a "upon successful login, execute cookies.set("x-auth-token", res.body.token)"
It's odd to me that it works locally at all. Would someone mind explaining how this works? I thought cookies were stored in the browser on the client side. But if that was true, why does cookie-parser even exist in express and why is it being used server side?
However, when I try logging in this using autodeployed branches in Vercel (https://vercel.com/), the cookie is missing.
This is because it appears you are setting the cookie server side, and as far as I know vercel only handles client side and will not let you use express.
I was under the impression that cookies were supposed to be set on the front end? But in the code the cookie is being set on the backend. And I don't see anything in the code that passes it to the front end. I thought I would find something on the front end like that would have a "upon successful login, execute cookies.set("x-auth-token", res.body.token)"
Cookies can actually be set through headers (Set-Cookie: <cookie-name>=<cookie-value>), which is what express's res.cookie does. MDN's article on the Set-Cookie header says:
The Set-Cookie HTTP response header is used to send a cookie from the server to the user agent, so the user agent can send it back to the server later. To send multiple cookies, multiple Set-Cookie headers should be sent in the same response.
It's odd to me that it works locally at all. Would someone mind explaining how this works? I thought cookies were stored in the browser on the client side. But if that was true, why does cookie-parser even exist in express and why is it being used server side?
Cookies are, in fact, stored client-side. They are accessible through client side javascript and backend with the cookie header. The cookie-parser module is needed to parse the name=value syntax sent by the Cookie header (Cookie - HTTP | MDN). It's being used server-side becuase validating cookies in the frontend can let any user give a false "true" value to your if statement that you use to validate cookies.
As an answer to the question: I recommend backend because JWTs have to be signed, and setting and signing them client-side will let anyone sign an arbitrary payload.
In PHP, getting cookies sent from a remote server is simply a matter of using cURL with some cookie handling option enabled.
If I was to treat my server as a client making requests to a remote server, I was wondering how this might be done in node.js? Would my server/app even be receiving these cookies? If so, how can I get the name and values of these cookies?
I've tried using the following node.js modules to no avail:
request (??? not part of functionality?)
tough-cookie (not part of functionality)
client-http (I get an empty array)
node-curl (I get an empty array)
Any pointers would be appreciated. Thanks!
You can use the http module that comes with Node.js
var http = require('http');
http.get('http://www.google.ca', function(res) {
console.log(res.headers['set-cookie']);
});
will give you all the cookies that google.ca would try to set on you when you visit.
I am creating a widget which will update some live NEWS happening. I want to push notification to the widget everytime I get some new information in my database. It is similar to live feed. I am unsure how to start this one in javascript.
I donot want to poll every nth second to get the information. I want the server to push information to the client everytime the server gets a new information.
It is similar to gmail. You get an email even without refreshing the page.
Any pointers will be definitely helpful.
You basically have 2 choices, what I can think of:
Using HTTP, you can ask the server every x second, if it has any new information, and if it does, then load & show it. If you are using HTTP, the server can't contact the client, it can only answer the clients requests.
Using sockets, you can create a 2 way communication, both the client can send data to the server, and the server can send data to the client. This way the server can send the information as soon, as possible. Here you can find information about the supported browsers.
Intermediate Node server can help to separate the business logic from polling operations.
Needs to install these packages - socket.io, express, request
npm install <package_names>
To get request data from node :
var socket = io.connect('http://localhost:3000');
socket.emit('pollNodeServer',JSON.stringify(requestToServer));
On server :
var http = require('http'),
request = require('request'),
app = require('express')(),
server = require('http').Server(app),
io = require('socket.io')(server);
server.listen(3000);
console.log('Server started at port 3000');
var options = {
headers : {
'Content-Type' : 'application/json',
'User-Agent' : 'request'
}
};
socket.on('pollNodeServer', function(data, callbackfn) {
requestServer(data,socket,callbackfn);
});
Reply from server :
socket.emit('returnJobs',JSON.parse(body));
The problem:
I just successfully got my Node.js server all working properly and setup with SSL, great. But then I see this:
[blocked] The page at 'https://www.mywebsite.com/' was loaded over
HTTPS, but ran insecure content from
'http://54.xxx.xxx.77:4546/socket.io/socket.io.js': this content
should also be loaded over HTTPS.
I tried just changing the socket.io URL to https, but of course that doesn't work because socket.io insists on serving it's own generated file, a process that I don't think I control. I can change the port that socket.io listens on, that's it.
The question:
So how do I securely serve socket.io (1.0)?
The codez:
var port = 4546;
var io = require('/node_modules/socket.io')(port);
As a side note, I think socket.io (its back and forth communication) should run over HTTPS properly without any extra work; I read that somewhere. Perhaps someone can confirm. It is important that the web socket's communications be securely transferred.
This is one of those occasions where the questions aren't quite duplicates, but the selected answer to a question answers this one as well.
It's simple: Just pass your https server object as socket.io's port parameter.
// ... require stuff
var app = express();
// ... set up your express middleware, etc
var server = https.createServer(sslOptions, app);
// attach your socket.io server to the express server
var io = require("socket.io").listen(server);
server.listen(port);
code by aembke