DEV Community

Cover image for Remaining Stateless - Using Redis for token blacklisting in Node JS

Remaining Stateless - Using Redis for token blacklisting in Node JS

Ogbonna Basil on July 22, 2019

JSON web tokens are stateless. That means the server does not maintain the state of the user. No information about who is sending a specific reques...
Collapse
 
gileri profile image
Eric G.

Sets are more suited for the case you describe (storing unique, unordered items) as they are faster for your case and avoid accidentally storing duplicates.

The complexity of looking up an item is O(1) with sets, while on average O(n/2) for lists.

Collapse
 
mr_cea profile image
Ogbonna Basil

Your Correct Eric , Sets have a bigO notation of O(1). However every token generated is always unique. Also the push method for a List is also an armotized O(1). But yes you can use sets

Collapse
 
dgroh profile image
Daniel Groh

Why don't u simply use Setx with the expiration date? Then just check if the token exists...Setx will automatically remove the token from the store once it expires even if you don't logout. Why should I keep a list of blacklisted tokens in Redis? Or did I miss the point?

Collapse
 
thegarlynch profile image
thegarlynch

you can also set expiration date for blacklisted item too. it will cause, lesser storage theoritically because you need to invalidate explicitly by logout. but it needs
"appendfsync always". otherwise, blacklisted item unintentionnally disappeared and make it worse than having authenticated token disappeared (since you can always login)

Collapse
 
princebillygk profile image
Prince Billy Graham Karmoker

I am also thinking so it will also remove the chance of duplication with deleting the token on expiration. This comment deserves more votes

Collapse
 
nargonath profile image
Jonas Pauthier

Just reacting to: "the token blacklisted and local storage can then be cleared." at the end explanation. You ought not to use localStorage to store your JWT otherwise you open yourself to XSS attack. You'd better be using httpOnly, secure Cookies to store it: thinktecture.com/en/identity/sames....

Collapse
 
mr_cea profile image
Ogbonna Basil

Thanks Jonas. I addressed these concerns in the other articles in this series

Collapse
 
_criztus profile image
Nmeregini Vincent

Awesome write up man

Collapse
 
mr_cea profile image
Ogbonna Basil

Thanks Vincent

Collapse
 
tabila7070 profile image
Mo Helmi

This is for token and not dealing with refresh token ?

Collapse
 
mr_cea profile image
Ogbonna Basil

Yes Mo. Even though the concept of using refresh tokens was briefly touched, the main focus is on handling authentication tokens themselves for better security.

Collapse
 
tabila7070 profile image
Mo Helmi

thanks