Node/Express: Session Sharing between Browser and Server - node.js

I can't seem to find anyone with the same issue - although I might have googled using the wrong questions.
I'm building a react app with server-side rendering. There is also another server which handles the entire API.
Here's the scenario I need to get working:
Initial website request initiated from user.
UI server loads the user from another API server
UI server then pre-renders all react components including the fetched user and sends it to the user
React component in browser needs to be able to fetch updated user information (from the api server, not the UI server)
So the problem is that I need to share the same session ID between the browser and the UI server.
I imagine it would work like this.
UI server requests user from API server.
UI server remembers session id from initial call and sets the cookie
Browser uses the set cookie for all future api requests and page refreshes
Is this achievable?

I would recommend you to use JSON Web Tokens instead of cookies. You can share the token in all of your services. It is the best way to authenticate user to use different apis at the same time.
Here is detailed tutorial for Node/Express

Related

How to trigger a service in Angular from NodeJS

I'm trying to do this.
I need to push data from NodeJS (backend) to Angular (frontend) without any explicit request from Angular to NodeJS.
I was thinking of making an API request to Angular from NodeJS and Angular would listen to the API request via a Service and fetch data accordingly.
I'm not sure whether this is the right approach or is it possible in the first place, could someone guide me in the right direction?
Edit:
I'm trying to implement this for multiple Social Media Integrations in a One Page MEAN App. On button clicks, users get redirected to respective Social media authentication pages, after successful authorization, I'm able to fetch the accessTokens in the backend. I'm confused about how to send the data to frontend without passing the accessTokens in URL parameters.
Is there any other approach to implement it in a MEAN app?
I think you can use socket module for pushing data from Nodejs to angular.
The socket module provides emit and on methods with the help of this you can broadcast data or send in the request also generate your own event please check this for more information
you should use tokens as like JWT (passport JWT strategy) and pass it to the client and store it in a cookie / local storage. you can use these tokens to protect api's and/or socket.io connects. after that you do whatever communication you want. the client needs to open the connection to the server (via pull or websockets) or you need to use some form of push service. The reason is, that for many clients they are behind address translation and cannot be reached directly.

How to let frontend know your server has successfully retrieved an access token

I've been studying the OAuth 2.0 authorization code flow and am trying to write a React application with an Express backend that displays what a user would see on their own Instagram profile. I'm trying to do so with minimal external libraries (i.e. not using passport-js) and without bringing a database into the mix.
This is my flow as of now:
Resource owner clicks an <a> tag on the React application (port 3000) which redirects them to the /auth/instagram endpoint of my Express server (port 8000)
res.redirect(AUTHORIZATON_URL) sends them to Instagram's authorization server
Resource owner consents and the authorization code is sent back to the predefined redirect-url /auth/instagram/callback with the authorization code set as a query parameter
I strip the authorization code off the url and make a POST request to https://api.instagram.com/oauth/access_token to grab the access token
Now that I have the access token, how do I reach out to the React frontend to let them know that everything worked and that the user was successfully authenticated?
From what I've read, this is where the idea of sessions and cookies come into play, but I haven't had luck finding documentation on how to achieve what I want without bringing in third party libraries.
In the end, I would like for my app to support multiple users viewing their profiles simultaneously. Since I imagine passing the access token to the frontend defeats the purpose of securely retrieving it on the backend, I'm guessing I will somehow need to pass a session id between the frontend and backend that is somehow linked to an access token.
Any ideas as to what my next steps should be are greatly appreciated, as well as any articles or documentation you see fit. Thanks!
Since you're doing the OAuth authentication on the server side, you have to pass some parameter to the redirect_uri, identifying the user session (see: Adding a query parameter to the Instagram auth redirect_uri doesn't work? );
When the redirect uri is called from the authority server, you will know which user was authorized. To notify the browser there are two options: 1) Notify the client using web sockets; 2) Pull the state from the client using a timer triggered function;

How do you handle navigation in a token-secured web application?

I have a rather conceptual question, I'm sure it's fairly stupid, but I can't figure it out.
So I am building a simple node.js app to learn, I want to make a web app which is has a set of REST web APIs for everything (including authentication), and then the presentation.
For authentication I am using token-based auth with PassportJS.
So when a user wants to access the site, he'll obtain a token from the authentication API, in turn he'll need to pass this token in a HTTP Header on each request to the app.
My question is, how is this handled in the code? When the app gets the token (for example from a login page which hits the auth API), should it attempt to store it in the local machine (for example LocalStorage, or Cookie) and then on each new page fetch it and use it in a Header? Should each page's javascript attempt to load the token from the local storage automatically? I tried looking for an example, but haven't found a complete one that deals with how you handle navigation when you're depending on sending a header on every single request (that you want authenticated).
Thanks!
Once the user is authenticated return a secure session cookie which will be stored by the user's browser. Now on every request, this cookie will be sent by the browser to your application automatically, which you can check in your backend code (typically controller) to verify the existence of user session.

Self Hosted Web API Authentication

I have a self hosted Web API running, which using DotNetOpenAuth to issue authorization tokens. Basically, the project consists of 2 ApiController endpoints (Authorize and Token). I would like to force the client to have to log in to a form, prior to being able to call either endpoint. (Forms Authentication I guess). However, doesn't seem like it works for self hosted Web API projects, so, I am trying to implement something myself.
As of now, when the user calls the Authorize web get method, I render the login page and force them to login. However, I would like to have a mechanism in place so that once the user logs in, I can send a cookie response. I understand that if you write the cookie in the response, the browser will automatically send any relevant cookies upon subsequent requests.
However, my test client uses a HttpWebRequest to call my web api. Do I have to build the mechanism to save the response cookie to a file on the hard disk, and then, read it back, and associate with the HttpWebRequest on subsequent requests? Or , is there something built into the framework which I can leverage (just like how a browser would automatically take care of this for me).
I figured that once I could figure this part out, I could just extend the AuthorizationFilterAttribute, and use that to check the validity of the incoming cookie.
Thanks. Any help or suggestion is appreciated!

The "right" way to do oAuth from a mobile client

I am building a cross platform mobile application (using the Xamarian tools, MonoTouch / MonoDroid). I am trying to work through the authentication workflow and am running into a stumbling block. I have searched all over for a clear answer and have yet to find it.
Here is an overview of my current setup.
I have a web site built in nodejs.
I use passport.js to do oAuth login on the web site. This works great, users can login to my site using Twitter or Facebook.
Now I want to extend this same login functionality to my mobile clients.
I see 2 options
Embed the app id and app secret's in the mobile clients and make direct oAuth calls to FB or Twitter from the mobile app
Proxy the oAuth calls through my existing nodejs web server (keeping the secret keys on the server)
Option 2 appears to be the preferred way (as it avoids having to "ship" the secret in the mobile apps).
I have the proxy approach mostly working.
I open a WebView in my mobile client and point it at http://mysever/auth/twitter
This runs through my existing passport.js code and redirects the mobile WebView over to the Twitter login page.
The user then enters their creds on the twitter webpage on the device.
Twitter then calls my oAuth callback URL (which is my nodejs web server).
My server and Twitter handle the back a fourth handshake of obtaining the user profile information (As I understand it, this is the key to this approach, my server and twitter handle the handshake, the mobile client doesn't have to do anything or pass any tokens during this process)
Here is my problem:
It is this last step that stumps me. Once the handshake is complete on my server I have the user information I need on the server and need to send it back to the mobile client application
I can't figure out any way in the WebView control to grab the response object and grab a cookie, or header value (for instance) (this seems true for Android and iOS). I don't think it is platform specific. I think I am trying to do something that a WebView widget in mobile platforms just don't suport. It makes me think I am missing something obvious.
The only thing I have figured out is to have my web server "redirect" the mobile client browser to a fake URL that has the user info in the querystring. Something like myapp://info?userid=1234
Then in the mobile app I can hijack the URL loading and grab this url and get the data I need. I can then stash this userinfo, close the WebView control and move on to a native screen in my mobile application and user the userinfo in any subsequent REST calls to my nodejs server as a means of identifying the user.
This is massively kludgy for multiple reasons. The biggest of which is that the url is sent over the wire unencrypted and has all the data in plain text.
There has to be a better way to get the data from the web server back to the mobile client?
Or am I doing it all wrong?
The most straightforward way to implement oauth for Xamarin, both for iOS and Android, is using Xamarin.Auth. The starter documentation for the client is here. I think it should maintain everything securely and you will not have to worry about having to use your node server as a proxy.
You will need to provide your Application ID as part of the calls, but I don't there are too many or any security issues to worry about there.
I know this is going against what you already have implemented, but maybe this could help simplify things a bit.
This is the same dilemma that I have been dealing with.
This is how I currently deal with it.
In my app the client can come directly or via another service such as facebook which is my main one and hence the one which I have concentrated on.
Facebook can either redirect via a POST (desk apps) or a GET (mobile).
I check the initial request so see if has a service identifier - here is the facebook GET for example.
app.get('/', function(req, res) {
var paraUrl = URL.parse(req.url,true).query;
//The fb_source is shown -
//i need to go striaght to the facebook authorization since
//its coming from
//from a mobile device.
if (paraUrl.fb_source){
res.redirect('/auth/facebook'); //this is the passport part
return;
}
res.sendfile('index.html');
}
The facebook POST is slightly different in that you get an access token encode in base64url. The GET gives you a code which you can exchange for an access token but I had problems with it and just opted for tying into the passport system.
If a client comes direct I check for the session or a encrypted cookie which ties into the local strategy. This then checks the db for an access token which can used to access the facebook api for example.
If a client is unrecognised they are given the option to authenticate via facebook, google etc.
The main thing is that only 2 pieces of information are stored with the client, the passport session id and my app user id
connect.sid - encypted cookie
userId - encypted cookie
I would be interested to find out how other people are dealing with issue

Resources