Securing API endpoints without authentication - node.js

I´m bulding a website showing data from my API endpoint. The website should be usable without a login form, but the API may only be accessible by using the website. What´s the best way of ensuring this?
It does not need to be 100% perfect, but I´m honestly overwhelmed by the good (and bad) solutions for this. The website is server-side rendered and could hand over an API token, but there are also Json Webtokens and sessions.
Webtokens seem to be good, because they can be set to expire a minute after creation. But with them, I have to keep track of their usage to avoid multiple logins using the same token.
And making it worse: Is there a way to enable users to reconnect to a websocket-api without reopening the website (single-use api tokens would be invalid)
I would love to hear your suggestions and (if you know a good place) to learn more about this.
Kind regards,
Max

Related

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.

Deploying a web app that has only one user

How would I go about deploying a web app intended for only a single user (myself)? I feel like making a login that only accepts 1 user is the wrong method and also easy to hack? Would it be a good idea to make it only accessible from a certain IP? Please advise! Thank you. Backend will be using nodejs.
If I were you, I would program the back-end the proper way. This involves generalizing the entire implementation so that any hypothetical user with the correct password could use your login system. You could still authorize and authenticate the application so that when anybody else tries to log in, you automatically decline their request. If you are concerned about security, ensure that you are using SSL, basic encryption, hash passwords and, most importantly, do not use your own authorization library. It is far more secure if you use OAuth instead of using an IP, for example. Last, but definitely not least, make it as hard as you can for hackers to steal your data in the client side. This way, you also learn a lot of things that might come in handy in the near future.

How to make Node API only accessible by web app?

I'm developing a web app with React and an GraphQL API with Node.js / Express. I would like to make the API more secure so that its harder for API requests that don't come from the web app on the browser to get data. I know how to do it with registered users. But how to make the non-registered user still be able to access some basic data needed for the app?
Is it possible to put some kind of key in the web app - so the API call can't be replicated for others through sniffing the network dev tool in browser and replicating in Postman? Does SSL/TLS also secure requests in that browser tool? Or use like a "standard" user for non-registered visitors?
Its a serverside web app with next.js
I know theres no 100% secure api but maybe its possible to make it harder for unauthorized access.
Edit:
I'm not sure if this is a problem about CSRF because Its not about accessing user data or changing data through malicious websites etc. But its about other people trying to use the website data (all GET requests to API) and can easily build there own web app on top of my api. So no one can easily query my api through simple Postman requests.
The quick answer is no you can't.
If you trying to prevent what can be describe as legit users form accessing your api you can't really do it. they can always fake the same logic and hit your webpage first before abusing the api. if this is what your trying to prevent your best bet is to add rate limiting to the api to prevent a single user from making too many request to your api (I'm the author of ralphi and
express-rate-limit is very popular).
But if you are actually trying to prevent another site form leaching of you and serving content to their users it is actually easier to solve.
Most browsers send Referrer header with the request you can check this header and see that requests are actually coming from users on your own site (this technique is called Leech Protection).
Leaching site can try and proxy request to your api but since they all going to come from the same IP they will hit your rate limiting and he can only serve a few users before being blocked.
One thing the Leecher site can do is try to cache your api so he wont have to make so many requests. if this is a possible case you are back to square one and you might need to manually block his IP once you notice such abuse. I would also check if it's legal cause he might be breaking the law.
Another option similar to Referrer is to use samesite cookies. they will only sent if the request is coming directly from your site. they are probably more reliable than the Referrer but not all browsers actually respect them.

How to make a proper and simple authentification for nodejs website?

I am learning to make a website with nodejsn, express, socket.io and mongodb. I am pretty much self-taught but when it comes to authentification, I can't find a tutorial that explains how it works in simple terms.
I have a login form, a signup form, the user data is stored into the database on registering. When I login, the page greets me with my username, but when I refresh or close the tab and come back, I have to login again.
All I want is that make users able to come back without having to log in systematically.
All I can find are explanations like : http://mherman.org/blog/2015/01/31/local-authentication-with-passport-and-express-4
And I don't really get it.
Can someone explain what am I missing here ?
Session management is something that Jekrb highlighted and is also a great question when it comes to highlighting users if it be anonymous or users of your application.
Though before I go into any depth I am going to highlight that cookies have a slight problem if your application is going to work on a larger scale where you have this scenario: "What happens if you have N servers where N > 1 ?" so to some degree if your unsure of your user-base, cookies may not be the correct approach.
I'm going to presume that you don't have this issue so providing cookies as a means of identifying users is appropriate, but isn't the only method available.
This article outlines a few ways in which the industry tackles this:
https://www.kompyte.com/5-ways-to-identify-your-users-without-using-cookies/
My favorite method here would be canvas fingerprinting using https://github.com/Valve/fingerprintjs2 Which will create a hash that you can store and use to verify new connections, Probably with something like socket.io which you've listed as using. A major upside of this is scalability as we can store these unique hashes centrally inside of the database without the fear of always being stuck with one server.
Finally I haven't posed any code which I dislike but the topic is hard to pin down to specifics, though I have hopefully offered some alternatives to just cookies.

Making my web api secure?

I am creating a simple web api that returns json.
It will perform simple crud operations.
What is the best way to authenticate users, OAuth seems to be the main recommendation here but I'm looking for something I can implement myself simply, token based or and API key??
Any ideas suggestions tips would be great, thanks
UPDATE: Forgot to mention, this API wont be for general comsumption, its just for my own use but I want to make sure someone cant get in too easily if they stumble on it.
First of all in order to build a good API you should use other people's API to see how they work. To be RESTful an API key is used, which is just a really big random number or "cryptographic nonce". But really this is just like immortal session id to look up a users authentication information, which isn't that great. OAuth is great, if you want your own system kerberos is very secure.
It is possible to hijack json responses, which is a pitfall against json. If the API key is required for each request, then the attacker can't use this method.

Resources