In HTTP Basic Authentication, why is it better to store a token? - node.js

I have a rich JS app in React running on HTTPS, and server-side I have an api in NodeJS listening for client requests. The users are not developers ; actually they barely use a computer. I want a simple login/password form (something they are familiar with) for them to authenticate.
Instead of storing the username/password client-side and include them in every api request, it is suggested to store a token. If I understand correctly, server-side in DB, this token is also stored alongside the username/password in the table of users.
What confuses me, is that this token would not be hashed (e.g. with bcrypt) like the password would. So isn't it like having a clear password in the database?
Well for sure I missed something important about tokens.
Then if anyone could lead me the path on how best to manage http basic authentication with a token in NodeJS, it would be really appreciated:)

Related

How can I secure my Node.js backend api data?

I may be a little confused about how backend servers work. Let's say I have a frontend React app with a login. The login information is stored in a database (i.e. MSSQL, MySQL, MongoDB) and I have a Node backend with routes for my app to fetch that information when a user is logging in or doing anything. When both my React app and server are hosted, I would make calls to the api and no confidential information (such as passwords) would be sent back to the client (just maybe a "success" message if the login information appears to be correct on the backend). My question is, what is stopping someone from finding the backend route and putting it into Insomnia to get the password or other sensitive information?
My first thought was to use express-session and auth on the backend to require a user to be logged in to an account to make such requests, but I think there are two issues with that:
How will that work when multiple users are logging in at once? Since the users are not technically physically visiting the api routes themselves, does session still know who is signing in to what account on the frontend? Will the second person logging in override the first person's session even though the first hasn't logged out yet?
If the auth doesn't kick in until a person is logged in, wouldn't someone be able to get the response password data from the login route itself?
Sorry if the question sounds dumb I'm just having a little trouble understanding the security aspect.
It sounds like there's a bit of a misunderstanding of how auth sessions work. There are two primary way sessions can work - either storing the sessions on the backend (older way), or storing session data in a cookie, typically a JWT (JSON Web Token). Cookies are bits of data that are passed from the server to the browser and anytime the browser makes a subsequent request to your server, it passes the cookie back too, so your server will always be able to get that data. The way this works for auth is the following:
A user signs into your application with credentials (username and password).
Your server validates the credentials by checking your database or wherever you're storing them and rejects the request if it fails. (Check out Auth0, Firebase Auth, or other auth services as doing this yourself can be a pain and open yourself up to potential vulnerabilities)
If the credentials are valid, the server generates a signed JWT token that includes data, like the username of the user.
The server responds with the body as well as a cookie containing the JWT, which the browser then stores.
The user requests some user-specific data from your server, and the browser sends the cookie with the JWT back to your server.
Your server validates that the JWT is valid by checking the signature. If it is valid, it uses the username from the token to get the user-specific data. If it is not valid, it rejects the request.
Because the signature occurs entirely on the server side (typically with some hashing algorithm and a secret key that you don't vend publicly), it would be nearly impossible for someone to spoof a JWT token signature. Therefor, your server is able to 1. trust that the JWT token is indeed valid if the signature is correct, and 2. find out what user is requesting data.
Here's a video that helps explain and visualize this: https://www.youtube.com/watch?v=soGRyl9ztjI
And here's a library for creating and validating JWTs in Node: https://www.npmjs.com/package/jsonwebtoken
Hopefully that answers your question!

User session between Express+Nodejs and clients using Firebase

what's a common approach of storing user sessions with Nodejs+Express and Firebase auth? I have Android and Ios app that I'd like to use the same logic on (later web as well), so I'd get the JWT token. I'd like to use that token as authorization for requests. Also I'd like to keep the user sessio and not require them to relogin again. I am not sure how to go about this, all of the Express Session resources I've found were on topic of web and cookies. I've stumbled upon MongoConnection a library for Express that presumably stores the sessions in the MongoDb, but how does the session work with non-web requests? Can anyone help me clarify this, I am aware that I am missing the point here as there is certainly an easy way to verify incoming requests and also have a session for the user to not have to login everytime.
Preferably I'd like to have an easy way to have endpoints that require JWT token access. Besides that also have a session of sorts. There is a function to verify tokens in the Firebase Admin SDK for Nodejs but it seems really weird to have to check the token manually in every request.
I treat sessions on the backend and front end entirely separately as I predominantly make RESTful apis. On the front end you can handle sessions however you like, e.g. you can start a session when a user authenticates with firebase auth, and set the user role maybe based of attributes on the firebase auth user. Use cookies, do whatever you prefer.
Then on the backend, on every endpoint just decode the token, verify it, check that the user has access to the resource they are requesting etc. Its common to write your own middlewares so that you dont have to repeat the decoding code. For further info on this approach, this might help. Its not weird to check the token manually on every request, its common practice to guarantee the authenticity of the request. Hope this is of some help.
To sum up, treat your front end session entirely separately from the backend. On your express server on the backend, on any protected endpoint decode and verify the token to determine if the user has access to the resource.
Backend sessions with firebase are a bad idea (due to it been serverless), its better to create a stateless restful api.

How to create a secure user authentication flow for a webapp? (VueJS | NodeJS | ExpressJS)

Problem:
I want to create a webapp with VueJS and a custom backend with NodeJS (ExperssJS and PostgreSQL). It should be possible to login with a username and password. After a successful login, the user can access secured endpoints of the ExpressJS server.
Now I am thinking how I can securely authenticate HTTP requests after a successful login.
What I consider doing:
Using a JWT and providing it in the authentication header of every request.
When the user provides correct login data, the server creates a JWT and sends it as response to the client. The client stores the token and adds it to every HTTP request as the authorization header. Because the transport is secured with TLS (HTTPS) the token should not be visible while transporting. To provide a seamless user experience the token has to be saved at the client side, so the user does not have to authenticate for each request.
So my question is: How can I securely save a JWT token for further HTTP request authentication?
Possible options:
LocalSotrage - BAD IDEA! (not really secure)
Cookie - more security (but also not perfect)
Last thoughts:
Isn't there an "absolute secure" or a "best practice" method to handle authentication for such a scenario?
P.S. I am pretty new to this field, so please forgive me if i wrote something stupid :D I am also aware that there are a lot of tutorials on how to setup something like this, but what i want to know is, which technique is the best and most secure one.
Thanks in advance!
PassportJS also support using local strategy. You might want to take a look about it. here
If you are new then it's better to use already build user authentication flow like Google login, Discord Login etc.
There is a well known library called Passport JS which makes third party login system integration a breeze.

ReST API: Should I associate the access token with a user in my database

I am building a secure ReST API on a nodeJS server so that my Android application can access the data on my site. Based on reading some other posts, I've come to understand that I should use an access token. So my idea is to do the following:
1) When the user logs in on the Android app, the app sends a request to /api/login on my site, providing the username and password (this of course needs to happen over SSL to guard against eavesdropping).
2) My server validates that the username + password match, and, if so, responds with an access token.
3) The app uses this access token to make all subsequent requests to my API.
My question is should I store the access token in the database on my server? Specifically, should I store the fact that the access token is associated with that particular user? Most tutorials I looked at did not do this, but if I don't, then what is to stop a user with this access token modifying or viewing the data of another user? Don't I need to pair an access token with a user in my database?
try using this library, i did the same type of project and this life saver was my solution.
If you need to build a secure API the things are little more complicated. You need to sign the access token with a private keystore.
Would it be a option to use a authentication service like Auth0? They are generating a JWT token for you and you only need to validate this token. The API is completely stateless. You can find a lib for almost any programming language on their website.
What you want to do is exactly HTTP Sessions do.
So, I think you can just use HTTP Session functionality It's already implemented in WAS frameworks like Django, Spring etc. If NodeJS provide session functionality, Just use session functionality in the framework. If not, look up the HTTP Session library. Maybe you can find many library that treat session implementation.

Restful API Authentication and Session management for Express.js

I have been researching on RESTful authentication alot, and I still can't get a very clear idea, how can I design my web architecture. I have many questions that are unanswered.
I want my API to be served to mobile and web too and I am using Express v4.
I don't want to use Basic Authentication, as many posts have suggested as a simple way out, or I can use the Passport middleware, but I want to use token based authentication or something similar or better,and I want to make my authentication, so I could understand better, but I am not sure how can I achieve it.
I will simplify my intended authentication architecture below:
Registration of a new user
Client side
Post username and password to server
(I know if you want to make the connection secured is to use https connection, or else I will expose my credentials, or you got any other options besides https? or else I will need to use the public and private key with timestamp and hash my credentials before sending to server? How can i do this? Is there any other better option?
Server side
Hashed the password using salt cryptography, and stored the hashed password and salt, then generate a token ID and sent to the client, and the token ID is stored in sessions or using the REDIS database?
Isn't that using sessions violates REST again? But, if I don't use sessions, how can I store the token ID and compare it with the client side?
Client side
Since now I have the token ID, how can I store on client side?
Should I use cookie? If yes, will this violate the RESTful? And how can my mobile application store the cookie too?
What other options can I have besides cookie? I can't think of any.
Authorizing API
Client side
Now, I have the token ID, I will place this in the authorization header each time I would like to make a request to the server.
Server side
When a request is received, the server will check the token API, and compare it with the session token, if it is true, request allow else reject
Is this a standard way for Express application authorization?
I am sorry for the lengthy post, but I feel that I should really master the authentication and authorization because it is important. I do hope someone can correct my misconception of REST authentication and answer my questions or suggest me a better way to do it.
Send the user credentials encoded over https
To compare the token at the client side you can either keep it in map or in Redis store corresponding to user id and match it to consider user authenticated. It does not kills the significance of Rest as in Rest as well authorization tokens are sessions only which after expiry
Express does not have any specific or standard method of authorization , it only enables you to use any db in backend to perform authentication and authorization as required by your application
Your solution is the use JWT tokens for your authentication .You can read more about JWT at https://medium.com/dev-bits/a-guide-for-adding-jwt-token-based-authentication-to-your-single-page-nodejs-applications-c403f7cf04f4
With JWT tokens you can have a token base auth system with no sessions UID at cookies , but you have to implement logic to handle tokens that have sign out something like blacklist tokens.

Resources