As far as i studied so far from stackoverflow answers regarding making sessions persistent after server restart.
There are 4 possible ways which i considering to do with my mean app.
cookie-Sessions https://www.npmjs.com/package/cookie-session
using Json web tokens (JWT) https://www.npmjs.com/package/jsonwebtoken
using connect-mongo/connect-redis
passport.js
Now my doubt is if i will restart my server in mongo and redis . session will still be there as they are external data stores.
but how to make my session persistent using JWT and cookie sessions.
where are these session variables are stored.
In case of passport.js the solution which i came across is to make session persistent is to store session data in connect-mongo/connect-redis.
is there any other way in passport to make sessions persistent?
If you store session at external storage, then after restart it should be available.
Passport is not responsible for sessions. You setup session independently from passport in express. Passport is authentication middleware with strategy to use your session.
you setup express session:
app.use(express.session(session options));
and after that you init and setup passport to use session:
app.use(passport.initialize());
app.use(passport.session());
It means that regardless of whether you use passport or not, session configuration will be the same.
there are few ways to make sessions persistent:
Most of them store session in db or in file system (memory storage is appropiate only in dev env). Please look at this npm search list link.
List of Compatible Session Stores from official express-session page https://github.com/expressjs/session#compatible-session-stores
Jwt token, if properly implemented, is stateless. It means that your server does not storage any session data, It doesnt know how many sessions are valid. It authorize request if it have valid jwt token.
Jwt token can store some data, like your user id. When your server receive token, it decode it and validate, then you have access to data from this token. Please read this article for more details :
https://stormpath.com/blog/jwt-the-right-way/
Most important parts (there are more important things, butthese are sometimes forgotten):
Always verify the signature before you trust any information in the JWT
and:
Do not contain any sensitive data in a JWT
Please look at this module for maintain jwt:
https://www.npmjs.com/package/json-web-token
or even for some hybrid solution module (redis session with jwt token):
https://www.npmjs.com/package/jwt-redis-session
Related
I'm trying to get the userId inside the websocket listener i've done a ton of google searches about the topic but without any progress.
I'm using passport ,express-session packages.
Please be more specific regarding user ID's. I see you are using passport to implement your session authentication. What particular passport authentication are you using? Passport Google Auth, passport Discord etc., there are plenty. Generally, the session data is what you are looking for if the user id is stored that way.
The session cookie or session store will contain the authentication data you are looking for. If you are using express-session, this information can be obtained by looking at the "req.user" aka Request user. Whatever you store for session data will come up in the req if the user is authenticated through Passport.
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.
I have a bunch of questions about express-session and JWT in a project that I am building.
I have an Express API server that I want to protect using some sort of API key, to make sure only authorized applications can access to my data. JWT would probably get the job done. However I also need to authenticate users and restrict them from accessing certain parts of the data (e.g. role-based permissions) using express-session.
The frontend server would be a Next.js instance, which would save and use the cookies for express-session. The session would be stored in a MongoDB instance.
Would I be able to use both authentication methods in the same project? Would it be secure? Is there any easier approach to this? How could I implement the permissions?
Any help and tips would be appreciated.
JWT and Express-Session both accomplish the same thing. The difference is a browser does not allows a http-only cookie to be accessible through javascript. At then end they are both used for the same end.
The jwt should be related to a session of a user, therefore the users permissions are the ones that matter. These can be implemented in a DBs and related to the user. Does he has this permission or does his role has this permission is the middleware you would put on the routes.
In case of doing it with express-session, I would personally take the same approach.
Is there any way to keep server side sessions in node js for requests coming through mobile applictions, Or it is in a way compulsory to use other methods like jwt?
As we do in Web applications, i.e Store the user information in the session on login and use the same information for later api calls.
Yes, there is and the simplest solutions is to use JWT, you can implement jwt authentication in you node.js server with any approach you want like: passport-jwt, express-jwt,... or even yourself with just jsonwebtoken npm package.
then for keeping mobile application authenticated with server, store the jwt token in mobile local storage and when app is opened just check the storage for if the token is exist or not and when there is jut add the token to the header and practically your mobile app keep a seesion open with server.
and for more information about jwt i ask a question about difference between session and cookie that might help you:
Authentication: JWT usage vs session
I'm working in a cookie-less way to manage sessions in my project (expressjs), keeping all session data server side and using a token at client side (previously generated by the server) to validate the session on every request.
A new token will be created on user login and kept hide somewhere in the page, then, on every request this token will be written to the request header and validated server side. at this point server will search for the token in a session store, lets say redis, and get the session data if the token is found or respond with a message of session expired otherwise.
There are some things i'm considering for this:
Redis keys are created on user login with a settled expiration.
Every time session data is found in redis i have to 'touch' the key
so expiration time gets postponed.
Token will be validated along side with the ip address of the client so can't be used by other person.
My question is if this is can be considered a secure way to work with, and if there is anything i'm missing here. Thanks
OK, cookies are required for storing session. Express does it the ideal way.
In express session(not cookiesession) it is completely stored at the server, only a key is sent to the client. The whole session is serialized to a key which is then sent. I assume you want that user cannot tamper with the session cookies. You can use httponly cookies to prevent tampering. They are only handled by browser and cannot be accessed by user. This prevents cookie theft or session hijacking. You can enable httponly cookies with:
app.use(express.session({cookie: { path: '/', httpOnly: true}, secret:'password'}));
Still you should use some encryption to prevent eavesdropping of cookies. Use secure : true for that. You can also mention where you want to store the session with redis, mongo or simply in memory.
The request token validation that you mention is a technique commonly used to prevent Cross-site request forgery. It keeps changing the token dynamically to keep user from getting the token. You can use this in express with csrf middleware.
app.use(express.csrf())
IP matching will not work as IP of user can change over time.