Asked  7 Months ago    Answers:  5   Viewed   22 times

For a new node.js project I'm working on, I'm thinking about switching over from a cookie based session approach (by this, I mean, storing an id to a key-value store containing user sessions in a user's browser) to a token-based session approach (no key-value store) using JSON Web Tokens (jwt).

The project is a game that utilizes socket.io - having a token-based session would be useful in such a scenario where there will be multiple communication channels in a single session (web and socket.io)

How would one provide token/session invalidation from the server using the jwt Approach?

I also wanted to understand what common (or uncommon) pitfalls/attacks I should look out for with this sort of paradigm. For example, if this paradigm is vulnerable to the same/different kinds of attacks as the session store/cookie-based approach.

So, say I have the following (adapted from this and this):

Session Store Login:

app.get('/login', function(request, response) {
    var user = {username: request.body.username, password: request.body.password };
    // Validate somehow
    validate(user, function(isValid, profile) {
        // Create session token
        var token= createSessionToken();

        // Add to a key-value database
        KeyValueStore.add({token: {userid: profile.id, expiresInMinutes: 60}});

        // The client should save this session token in a cookie
        response.json({sessionToken: token});
    });
}

Token-Based Login:

var jwt = require('jsonwebtoken');
app.get('/login', function(request, response) {
    var user = {username: request.body.username, password: request.body.password };
    // Validate somehow
    validate(user, function(isValid, profile) {
        var token = jwt.sign(profile, 'My Super Secret', {expiresInMinutes: 60});
        response.json({token: token});
    });
}

--

A logout (or invalidate) for the Session Store approach would require an update to the KeyValueStore database with the specified token.

It seems like such a mechanism would not exist in the token-based approach since the token itself would contain the info that would normally exist in the key-value store.

 Answers

20

I too have been researching this question, and while none of the ideas below are complete solutions, they might help others rule out ideas, or provide further ones.

1) Simply remove the token from the client

Obviously this does nothing for server side security, but it does stop an attacker by removing the token from existence (ie. they would have to have stolen the token prior to logout).

2) Create a token blocklist

You could store the invalid tokens until their initial expiry date, and compare them against incoming requests. This seems to negate the reason for going fully token based in the first place though, as you would need to touch the database for every request. The storage size would likely be lower though, as you would only need to store tokens that were between logout & expiry time (this is a gut feeling, and is definitely dependent on context).

3) Just keep token expiry times short and rotate them often

If you keep the token expiry times at short enough intervals, and have the running client keep track and request updates when necessary, number 1 would effectively work as a complete logout system. The problem with this method, is that it makes it impossible to keep the user logged in between closes of the client code (depending on how long you make the expiry interval).

Contingency Plans

If there ever was an emergency, or a user token was compromised, one thing you could do is allow the user to change an underlying user lookup ID with their login credentials. This would render all associated tokens invalid, as the associated user would no longer be able to be found.

I also wanted to note that it is a good idea to include the last login date with the token, so that you are able to enforce a relogin after some distant period of time.

In terms of similarities/differences with regards to attacks using tokens, this post addresses the question: https://github.com/dentarg/blog/blob/master/_posts/2014-01-07-angularjs-authentication-with-cookies-vs-token.markdown

Tuesday, June 1, 2021
 
turik
answered 7 Months ago
61

For the session management we need a middleware 'cookie-parser'.Previously it is the part of express but after express 4.0 and later it is a separate module.

So to access the cookie parser we need to install in our project as :

npm install cookie-parser --save

Then add this into your app.js file as :

var cookieParser = require('cookie-parser');

 app.use(cookieParser()); 

Then we reqired session module. So first of all install the session module by :

npm install express-session --save

Then to enable the session. we add below code in app.js file.

app.use(session({secret:config.sessionSecret, saveUninitialized : true, resave : true}));

Then come to the routes.js file :-

Let us suppose there is a session variable favColor. Now using session set the color and get in the other page. the code is look like :-

router.get('/setColor', function(req , res , next){
        req.session.favColor = 'Red';
        res.send('Setting favourite color ...!');
    });
    
    router.get('/getColor', function(req , res , next){
        res.send('Favourite Color : ' + (req.session.favColor == undefined?"NOT FOUND":req.session.favColor));
    });

This is all about the session management.We can also learn more about the session :- This Reference

Thursday, August 5, 2021
 
Vikram
answered 4 Months ago
93

A JSONP call doesn't work without a callback. The data is loaded in a script tag, and if the code is not in a form of a method call, the result would just be an object that was discarded, and the success callback method would never be called.

The ajax method is adding a callback parameter to the URL even if you don't specify one.

In the documentation, under the "jsonp" value for the dataType setting:

"Adds an extra "?callback=?" to the end of your URL to specify the callback."

http://api.jquery.com/jQuery.ajax/

Thursday, August 26, 2021
 
CMOS
answered 4 Months ago
46

here is a link for a tutorial for consuming JSON web services from an iPhone app.

Sunday, October 24, 2021
 
Mikita Belahlazau
answered 2 Months ago
39

The problem is that the routes are set up before any other middleware. Move this line:

require('./router/main')(app, language, connection, logger);

after this:

app.use(session({
    secret: 'pecuniamsekretsession',
    resave: false,
    saveUninitialized: true,
    cookie: { secure: true }
}));

in your server.js.

Friday, November 26, 2021
 
nirvair
answered 2 Weeks ago
Only authorized users can answer the question. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :
 
Share