NodeJS - Session handling WITHOUT express - javascript

I have built my app, I used plain JS on NodeJS and it is a single-page app. I didn't use express.
First the user needs to log in. The login-data is sent via websocket to the server and there the credentials are checked against a MySql-DB. If they are correct, the loggedIn-content is generated and sent back to the client, where it is displayed.
Now when a user is already logged in, and then refreshes the browser, he lands on the initial state of the app, and needs to log in again.
how can I fix this?
I read a lot about session-handling in NodeJS, but most articles include express, which confuses me to understand this whole concept.

HTTP itself is stateless, so you need some sort of way to identify the user.
Traditionally, this is done via cookies. When you respond to an HTTP request, you include a cookie in your response headers. For all subsequent HTTP requests, the client will include this cookie information back to you.
This means that you can send some sort of session identifier, and for all future requests you can look up the session data. The conversation goes a bit like this.
Client: Here's my login information, and I'd like the home page.
Server: Ok, thanks. Here's the home page. Also, remember that your session ID is 12345. Next time you ask me for something, tell me that session ID. (Logs in the database that session ID 12345 is associated with someuser.)
Then later...
Client: I'd like this other page. You told me to tell you that my session ID is 12345.
Server: (Loads session information for 12345, sees that it's associated with someuser.) Ok, here's that other page.
How you actually do the storage of all that is up to you. Many folks use databases, since they're often already using them for the application and it makes it easy to share session data with multiple instances of the application server.

Related

How to store and use sensitive data in ReactJS

I am doing a Website 100% in ReactJS, It's a simple/medium complex, this has a Login, Profile and other sections more. After Users Log into the site the login callback returns some important values like: "Token, UserRole". Currently I'm storing these values in Web client using localStorage .
My doubt is the next: There is a better way to store this values? Because if any person changes the value from the Browser Console this could be a BIG ISSUE because they could change the role and then execute things that they never should do.
I thought to do it with Redux, but if the users Refresh the website then they lost the values, so I am not pretty sure to choose this.
What do you think guys?
TIA!
The general rule is to never trust any data stored client-side, except for an authentication token or the equivalent. All changes that the user makes that involves the server should be verified on the server. So, rather than:
if any person changes the value from the Browser Console this could be a BIG ISSUE because they could change the role and then execute things that they never should do
Instead, the right thing to do would be, when the client wants to do something (such as edit their profile), have the client send their authentication token (or session ID) with the rest of the payload to your server. Have your server examine the token, check that the user associated with the token actually does have the required permissions for what they want to do, and only then continue to process the request.
Whether you also happen to store some information in Redux or elsewhere has no impact.
Storing login-related information client-side is relatively common and isn't inherently bad - just make sure to always verify it on the server when something that requires permissions is requested.
One approach some use is for the server to create an encrypted JWT that only the server can decode, which gets sent with requests.

how the session will map back to server if it reboots

I have dough't i have a server page written in asp.net and i have used session in pages. For example (an user login and start working in page for 10-15 min) while working there was some issue and my server is down and starts again. Now think i have given session timeout=20, how will my session id will know this is my server or how it works i have asked many people i am not satisfied with their answers. Please can any body help me with this issue.
Thanks in advance..
If you're using InProc session state (the default in ASP.NET) you will lose all session data on a reboot. To prevent this from happening you will have to configure out-of-process session state in the Web.Config and have a State Server or SQL Server that keeps the session state data.
Note that if you choose to do this, everything you put into session state must be serializable as it is serialized before sending to the state server.
Edit
To set up a state server, Microsoft has some pretty decent docs on the Technet site here: State server or Sql Server. Additionally, searching for out of process session aspnet will give you some excellent blogs on the subject.
Do note that if you want to protect against reboots of the webserver, the State Server service should not run on the same machine as the webserver. When using Sql server this is obviously less of an issue.

How to use JWT for a proxy server written using Node.js?

This is absolutely a newbie question & I am Node.js beginner.
I am not sure, this is right place to ask this question. But I may need idea from this large community. So let me explain what I am trying to do.
Server Configurations:
Node.js - 4.0.0
Hapi.js - 10.0.0
Redis
Scenario:
I am writing a proxy server in nodejs using hapijs. My Backend is ATG based e-commerce website and my api's are going to be consumed by web browser, mobile app etc..
We planned not to send the cookies sent by ATG to both browser and mobile.
So to maintain sessions and cookies from ATG,this is how we done POC.
First We planned without considering storing the anonymous user cookies returned from ATG. So we have done two POC's.
(Many of us know, what anonymous cookie is,any way let me explain that, if I put that one word -- Guest Checkout. There are many ways to accomplish this. But my Commerce Backend is implemented like this, When we go to website, you add items to cart and checkout that items without logging in right ? This what happens on background whenever we add the items they are only stored in your browser cookie,it not stored in persistent database, in any case user wants to login/signup to the account that cookie is retrieved from the browser and stored in database (basically that anonymous cart is transferred to logged in user.))
POC-1 (Not Considering Guest Checkout):
To access my api, user must be logged-in, after the successful login, We generate a rand-token and store it in Redis db associated with the cookies sent from the ATG for logged-in user and set ttl for 1 hour and return that token to the client
Now whenever they invoke any of api methods, they should send the token in the authorization header, I will check for token validity and expand the ttl once again for 1 hour and retrieve the cookies associated with that token, set that cookies in ATG request options and make a request.
3.On logout, I will clear the cookie and delete the token.
I have successfully implemented JWT fot this scenario, by generating a JWT token with user logged-in information in jwt payload. Used hapi-jwt-auth2.
POC-2 (With Maintaining Guest Cookies),
My API Will have endpoint /auth/generatesession, which in turn will return a 64 byte random token (we are using rand-token npm module for that) which will expire in 24 hours.
All the methods needs that access token passed back to me in authorization header and I will extend that token ttl to 24 hours.
Now they can invoke any api methods, like addtocart or something, even after adding items to cart , suddenly they want to login or something I can use their guest session cookie and transfer that cart to persistent database after successful login.
Questions:
Should I use JWT for the second scenario? If so,
How can I implement JWT for the Second Scenario? (Coz, don't know about who is the user?)
Does anyone think this is good idea for writing proxy server like this?
How can streamline session expiry of this token with ATG session Expiry?
Does anyone of using Node.js like this? How does it scale ?
If anyone care to give me an idea how to write this proxy server, it will be much helpful for me.
I Apologize, if this is too long question, just my way of explaining things.
Thanks in advance.
Sure, why not?
You don't necessarily need a user. A JWT stores arbitrary data, the username can be blank or anonymous. If a user logs it, and provides a token associated with a guest cart, then it can be assumed that that user is allowed to claim the contents of that cart, and the anonymous cart can be destroyed.
Sure, this is quite common (disclaimer: I've worked on something very much the same as you).
TTL is reasonable, but I have no idea what ATG is or how it handles it.
Yes. It scales very well as long as you ensure your servers are stateless, and that you manage all your state through something like Redis.
Too broad of a question, I would just use Express + Redis/Mongo/Postgres.

Where is best place to store authorization data when I use Backbone and AMD modules?

I create js app with Backbone and RequireJS for registred or non registred users. To retrive data from database I use simple JSON web service and of course some of methods are not avaiable for quest. Problem is that I don't know where or how I should store auth data retrive from server without reloading it in every view. Should I use cookies ?
I guess it depends on your authentication, authorization methods as well as the kind of security you need to consider for your users. If you're trying to be RESTful, you can't have sessions to save state (at least server-side). You could, but it wouldn't be RESTful due to saving of state on the server, if that matters to you. I've heard that it is okay to save state client-side but from what I've read, I'm not sure how the community feels about certain implementations that take this approach. (Like cookies, I'll revisit this later.)
Say you have someone login with username and password. You can hold that information in your Backbone app, maybe you have a model called AUTH that does this. Each time you make a request to the server you'd send that data each trip at which point the server authenticates and gives or rejects access to given resources. If you use Basic Auth this information would be in the header I think. Using SSL mitigates some of the major security concerns surrounding the sending of this information over the wire and for the rest of the discussion let's assume this is what we are using.
The other way that you could do this is to use encrypted cookie, encrypted cookie sessions. This is what I do with my current application. Honestly, I don't know if this is considered a violation of RESTful principles or not. The general chatter on the web seems to be a lot of "cookies bad, sessions bad" with some people saying, "get real." Using cookies would expose you to cookie hijacking if someone had access to the users computer, but depending on your application and the security needs it might not be an unreasonable option. It works for me and if it isn't RESTful, I like to call it RESTLike.
To close I'll just describe my setup. It would be nice to get your thoughts as well as the Stack's opinions on this also.
Basically I have a setup where when someone goes to the main page, the server checks for the encrypted cookie session. If the cookie session is invalid or non-existent, it gives the user the regular page with a chance to login. When they login, I send that information over POST so it's in the body of the request rather than the URI. (This is technically a violation of the REST HTTP verb concept since you use POST to save a resource.) When that information is processed, check the username, pass hash created by a unique salt, then the server creates an encrypted session cookie and passes it back to the user. Now, each time my user hits a route that requires authentication, the server checks the cookie to make sure it is still valid (time limit, user information, etc.) and if so - allows access. If not, it destroys the cookie information and sends back an appropriate status code. The backbone app reacts to this by resetting any view and data that shouldn't be in the hands of an unauthenticated user and shows them the login screen.
Hope this gives you an idea. This is the answer to how I do it, but if someone has criticisms or better ideas I'd be happy to upvote them instead.

Chrome extension / web app session control

I am creating a chrome extension, rather a chrome webapp. This application just contains the html, js, image and css files. The application connects to a server to fetch data. I chose to do this as it would reduce the amount of files downloaded by the user. Using Backbone.js I have an MVC architecture in my application. Thus the application just sends json.
Now having said this, I need a session management. I plan to use Google authentication as the organization has Google Apps. I need a method that once the user has logged in using google auth the server get the user name every time the application makes a request.
Is it a good idea to add the user name in request header, if possible. Or should I use cookies? Can any one tell me how I could go about using cookies in this case?
This might be a late response but I want to present a more elegant solution to you given that the user has cookies enabled in their browser.
First read my answer on another question.
Now that you can send cross origin xhr from your content scripts all you need to do is store all your authentication and session management at server only. That is right, you just need to display whether the user is logged in or not and a logout button at client based on server response.
Just follow these steps.
At client Whenever user accesses your chrome web app, blindly make XmlHttpRequests to your server without worrying about authentication, just keep a tab on response from server which I describe below.
At server whenever you receive a request check for valid sessions or session cookie. If session is valid send proper response, if not send error, 401 or any other response to communicate to your client that session is not valid. It is better if you send an error code like 401 since then you can put a generic script at client to inform them that they are not logged in.
At Client If response from server is proper, display it, else display login link to your website.
IMPORTANT: Display logout button if user is logged in.
Check out my implementation of this in my extension
For help using Google authentication in your app take a look at Google's OAuth tutorial which comes with all you need (took me no time to set it up using this).
As for session management. The implementation of OAuth used by Google stores the tokens in localStorage. Also, as briefly mentioned in the extensions overview we are expected to use localStorage to store data. Thus, I suggest you store the users name here as it will be accessible throughout the app's lifetime (until it is uninstalled). However, you may need to manage the name stored here and consider what should happen when users log in and out. That said; I'm not sure if sessionStorage would be a better option as I've never used it before, let alone in an extension.
Note
localStorage and its counterparts only store strings so I suggest using a wrapper which uses JSON to parse and stringify to get and set your values respectively.

Categories

Resources