Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

sh1r3f's avatar

How to implement 2FA on API access tokens through cache?

I already have my code that implements 2 factor authentication on web routes. The idea is simple: I've two columns in users table: 2fa_code for the verification code sent to mobile, and 2fa_expiry which is always set for 10 mins after sending. When user logs in a random 2fa_code is generated and sent to his mobile. then a middleware checks if 2fa_code is not null then redirects him to verification page to enter his code. If entered successfully we set the value to null. pretty simple isn't it?

the problem starts appearing in access token API. a single user can login multiple times from different devices. The problem now we have only 1 code column to users table so if user logs in again he overrides the values of the first login!

I'll try to get over this problem by implementing another situation for API. I want to handle it with cache. What I'm thinking of is. when user logs in a code is generated and instead of storing in database I will store it in cache. then the middleware checks if the cache has a code that is not null then user has to verify. if verified the code set to null which makes him allowed to visit whatever he wants to visit.

The problem now is: When user logs in and the code generated in cache. what if he doesn't do anything till the cache is expired? then when he tries to go to middlewared routes he will be dealed with as a verified user! and even if I try to overcome this by setting the middleware to check if the cache expired. he will be asked every 1 hour to verify two factor authentication! zero user experience!

TLDR; So how can I implement two factor authentication to API handled by cache?

0 likes
0 replies

Please or to participate in this conversation.