How to use localStorage Carefully in Angular - node.js

Since localStorage data can be changed easily, how can we make access controls and more things secure in the Angular App.
Suppose our localstorage contains:
data - {name:user, account_status:inactive,...}
The user can easily change the account_status from inactive to active and get all access.
I am not just concerned about access control but also the other localstorage data which is used in angular.
Can I encrypt the data from the node server and store it in localstorage and decrypt it back when i want to use with the same secret key. Will this have some adverse effects.
Please suggest some methods which can be used.

You can create a common service for localstorage operation which will perform the encryption when storing data in localstorage and decryption when getting data from localstorage. You should encrypt key and value both so it is not easy to change the value in localstorage. You can use CryptoJS for encryption.

That's execalty what happened back in the time with Spotify. The result ? With a little script, you could have spotify premium for free.
My point is, that you should not store sensitive data in the client side, and if you do so and use it, there should be a doucble checking (one from the client, one from the server) : if the user changes the values of the client, the server will check the validity of the requests anyway, and refuse resources to the user.
To finish, my point is that you don't need to encrypt your data, or to stop using local storage : just be clever and double-check the user permissions.

The type data you are trying to store should never to stored on local-storage, especially for a serious production app. Data should always be hashed/encrypted on the server and then sent to the front end for further manipulation.

Related

is electron's `safeStorage` for passwords and login credentials?

I need to store login credentials with electron js because it doesnt save them like all browsers. I have seen a lot of questions like this, but I never found a solution. I have seen in the electron docs about the safeStorage feature. is the it safe enough/good enough to store login credentials on the client side? if not what other tools are available to do that? I have heard about keytar but is it good?
The safeStorage api in electron exposes OS-level encryption/decryption using current user's secret key - please refer to electron source and chromium's os_crypt. On windows it utilizes DPAPI while on *nixes it uses whatever password manager the OS has as the documentation suggested.
is the it safe enough/good enough to store login credentials on the client side?
Depends, you should define "secure" first.
Ask yourself, should the same user allowed to read whatever value inside the encrypted text? A tech-literate person might write his own tools to decrypt things you store using that API you are out of luck. See this QA for further discussion.
if not what other tools are available to do that?
There are a lot of tools (and encryption algorithm) to encrypt stuff in nodejs. However, you have to remember an encryption require you to have a key of some sort and the key need to be protected too. Hence, try your best to avoid egg-chicken problem with your key of keys.
OS-based key storage avoids the key of keys problem by storing the "master key" in a way that only accessible using its API. At runtime, you can't retrieve the key at all, you just send a set of bytes for the OS to magically encrypt/decrypt. While at rest, the OS may rely on secure storage such as TPM (Trusted Platform Module).
is electron's safeStorage for passwords and login credentials?
Depends, if you are running a web service it is preferrable to not doing so. You should never dump end user's user name/password directly on a storage that you can't guarantee its safety by yourself (e.g. your server). You should, put an identifier which can be revoked or may expire at later date - token or cookies.
Imagine the trouble when your end user device get stolen. If it's a token/cookie, they can request you to revoke their access from that device - similar to "Log me out from all other device."
However, if its an in-situ application that authenticates to itself then its a fair game - though keep in mind about the first point. Its all down to your security model.

Having one backend manage authentication for a webapp and react native app

Im planning on making an application that has two parts two it:
React native mobile app
Browser web-app for desktop users
I'm trying to plan out how im going to manage the backend authentication for this (Node.js, passport.js). Ideally, I can just have one backend manage it, regardless of which type of client.
Lets say im going to ONLY have google auth (for simplicity). I don't need to hit googles API's for any information (like profile, contacts, etc), I just want them to login with a google account. My understanding so far is that theres two main ways (especially since im using passport.js).
jwt based approach
session based approach
For either approach, my issue arises when it comes to the react native app. Since I'm not able to use the HttpOnly cookie, im not sure how to safely store data. e.g
In the jwt approach, if the server administers an access token and a refresh token, the react native client can just store them both in the same place e.g https://github.com/mcodex/react-native-sensitive-info. Which means the refresh token is just as susceptible as the access token, which defeats the point of a refresh token, so might as well just have the access token be long lived.
In the session based approach, react native can just store the session id some where (like react-native-sensitive-info above), and the same problem arises
My current thoughts on what should be done:
It seems like theres no way of getting around the security issue of storing information in react native, so as of now I feel like im just going to follow the JWT approach, and store the access + refresh token in react-native-sensitive-info. However, this does mean that the login endpoint is going to return the access + refresh token in the body of the request when the User-agent is mobile. When the user agent is web then we should be able to set an httponly cookie. The only thing that I can think of is if there is a malicious request that masks the user agent (is this possible?), and then can receive the access + refresh token in the body and will be able to do whatever with that.
Performance Aside
A session based storage approach seems much simpler overall. Yes it does store state on the backend, but if we did the JWT approach we would have to store peoples refresh tokens somewhere on the backend anyway (If theres ever a scenario where we need to invalidate peoples refresh tokens, e.g on logout or damage prevention).
This way, say we have a sessions table, when a user logs out, or if we want to invalidate sessions, all we have to do is delete rows from that table. In the JWT method, if we want to invalidate a refresh token, we have to have a blocklist table (which will only keep growing in size, since refresh tokens shouldn't expire, but I guess they can be dropped after a long period of time). However, if you have LOTS of users, the sessions table could get large, which could cause performance issues (but you could probably just drop sessions over a certain age)
/Aside
Questions:
Ive noticed mobile applications have NEVER asked me to relogin with OAuth. Does that mean they're constantly using their refresh token whenever the access token expires? If theres no clear way to store that in a secure way in mobile, do they just have super long lasting access tokens?
Is all of this thinking overkill? Is it fine to just store a super long-lasting access-token in react native and just use that all the time? Then when the user presses 'logout' we can drop that from local storage?
Would a third party auth system like auth0 manage all of this for me?
I'll try to share my experiencies in different kinds of app, this way things may get more clear.
Authentication Method
On most of the mobile applications (with web applications) I've worked with long term access tokens on the mobile side, most of applications don't require the user to login each time you open the app. Usually we store the token in a Secure Storage.
In some cases I've worked with a memory database (Redis) to put the user's session it's really fast and you don't need to query your main database each request (this was used for a high availability system, it may be overkill for most usecases)
Some very specific solutions may require more security, this will depend on your product (like banks, and transactions apps or apps the keep sensitive data) in these cases I would recommend you to login the user every time he closes the app or stays inactive for to long. (this kind of solution usually relies on fingerprint/faceId libs)
My personal opinion on this matter is to go with jwt, it's easy to maintain on the server side if you need to change backends and has a more defined pattern to follow, but that's my opinion and if you have high demand or some specific usecase this may change.
Storage
Talking about the storage options, there are some good suggestions on where to save data like tokens in a secure way on the react native docs,a good option I've used sometime would be:
https://github.com/emeraldsanto/react-native-encrypted-storage
but you can see more options and it advantages here:
https://reactnative.dev/docs/security#secure-storage
Third party libs
They usually helps with the basics if your projects has the budget and not a lot of customization on the authentication process, usually if it's a brand new project (on the back and front end) they work well.
Most of them will handle most of the hurdle for you like token renovation but you should mind the price scalability for these kind of approach
Wish success on your project.

Where should I store access token

I am currently working on a chatbot for Facebook Messenger. I am working with the Microsoft bot framework and the code is written in node.js.
I am interacting with a database through an api. With every request I have to pass an access token inside the request header. I have read on the internet that you would usually store such a token inside a cookie or web storage. However I also found out that you can't do that on Facebook Messenger. I was thinking about storing the access token inside a variable, but my concern is that this might not be secure. Is there any other secure way to store the access token?
I am fairly new to node.js and it is my first time working with tokens. Help is much appreciated.
You can use session.userData to hold your database token. If you are concerned about it being secure, then encrypted it before saving.
session.userData.dbtoken = encryptToken(token);
The token can later be retrieved and used when you need it:
var token = decryptToken(session.userData.dbtoken);
var databaseData = getUserDataFromDatabase(token);
https://docs.botframework.com/en-us/core-concepts/userdata/
Or, use a local database like NeDB: https://github.com/louischatriot/nedb This would be the most secure option, since the database would reside on your server.
I would suggest using express-session. for the following reasons.
Create a session middleware with the given options.
Note Session data is not saved in the cookie itself, just the session ID. Session data is stored server-side.
Note Since version 1.5.0, the cookie-parser middleware no longer needs to be used for this module to work. This module now directly reads and writes cookies on req/res. Using cookie-parser may result in issues if the secret is not the same between this module and cookie-parser.
Warning The default server-side session storage, MemoryStore, is purposely not designed for a production environment. It will leak memory under most conditions, does not scale past a single process, and is meant for debugging and developing.
Assuming this token does not change, you can store it as an environment variable, say TOKEN and access it in nodejs app as process.env.TOKEN.

Trying to understand login systems and sessions

Im trying to understand how a user can keep logged (i'm trying to implement this on Node without frameworks, for learning). Just a couple of questions based on what i think i understand:
(1) When the user tries to login, it sends the user and password in an HTTP request body
(2) When data arrives to the server, it checks everything needed like if the user exists and if the password is correct
And here comes, i think, my problem: How can the user keep logged? The third step would be something like:
(3) The server create all the session data needed, encrypts and send it to the client?
(4) The clients store the encrypted data in the localstorage
(5) The credentials are sended with every request to the server, and the server decrypts it and check it before processing every user's action.
That's what i understand. But i find this very extrange. I feel i missing a lot... storing data in client side doesn't seems (at least for me) secure. Should the session data be stored on server-side? And how the username and password should be sended securely? It must be encrypted client-side? Is this secure? I think im looking for some pattern or i don't know. I feel lost.
Yeah, and sorry my bad english and poor knowledge. Im not asking for code and i will also appreciate any hint (like what to search in google, or a interesting blog) :)
Thank you, y un abrazo :)
--- EDIT ---
Well, finally i founded some usefull links and solved great part of my doubts :)
[http://stackoverflow.com/questions/6922145/what-is-the-difference-between-server-side-cookie-and-client-side-cookie][1]
[http://blog.codinghorror.com/protecting-your-cookies-httponly/][2]
[http://www.cse.msu.edu/~alexliu/publications/Cookie/cookie.pdf][3]
[https://es.wikipedia.org/wiki/Cookie_(inform%C3%A1tica)][4]
[https://newspaint.wordpress.com/2015/09/06/how-to-get-cookies-from-node-js-http-response/][5]
1 and 2 are correct.
Sessions are usually implemented using cookies, not client-side local storage, because cookies are automatically sent to the server with each request. The cookie will often contain just a long randomly generated ID which refers to data stored on the server side, e.g. in a database. This data will identify the user and possibly store other session-level settings.
It is also possible to use a cookie with signed (and possibly encrypted) user information - for instance ASP.NET does this by default. This has the benefit that no storage is required for the session. The downside is that sessions cannot easily be destroyed from the server side. Therefore e.g. a feature that shows the user their currently active sessions (from other devices) and allows them to log them out couldn't be implemented.
Sending the username and password over the Internet should preferably be done securely, by using HTTPS. Do not implement your own encryption on the client-side. It will likely not work, plus the cookies themselves are viable to be stolen if the connection is not properly encrypted and authenticated.

General user session handling (Nodejs)

I wrote a simple webserver with nodejs and express. I implemented an user authentication with email username and password. Furthermore I have a remember-function which stores the user id and pwd hash into a cookie. Now I would like an extra session that ends when the user will close his browser or click to the logout button.
Which way is the best practice for implementation? Is the session the same like the remember-function with an expire time and in each request I must check the credentials against the database? (I'm not that sure about this)
Technologies that I'm using: nodejs, express, mongodb
This is not a nodejs question only, I would prefer a general explanation for the problem.
Let me get this out of the way first; Storing the password hash into a cookie would allow anyone to login when they have the password hash and that would be disastrous if the password hashes ever got exposed for some reason. Encrypting cookies is just fine, but don't allow the actual hash you store in the database to be used for authentication. Ever.
About re-authentication, Node is a technology that operates on a single thread and is scaled by running more instances over multiple processors and/or machines. Keeping sessions is a good idea to avoid trips to the database, but you have to think about the architecture as well. What happens if you, say, use sessions stored in files (ala PHP) and you need to scale to multiple machines? Nothing good, at least. So you need a central point to keep track of the sessions.
This can be either your database (MongoDB) or something such as Redis, or another centralized mechanism allowing you to check sessions. Either way, you will have to spend time doing the request and retrieving the session values for the client. If you do not have additional values you need to store it makes no sense to create a dedicated session architecture (that needs expiration, and so forth) and just doing the authentication again is the easiest and most logical solution.
Personally I almost never need sessions and just do authentication again.

Resources