Home > front end >  Difference between Token based and Session based Authentication
Difference between Token based and Session based Authentication

Time:02-05

So, I've implemented some form of auth on my API, I'm not sure which kind it classifies as.

What my app does is, it generates a token once a user signs up/logs in and then before every endpoint call, I have a middleware function that checks if a token exists, then decrypts it, and if it's correct then its stores the user info in req.user. I then use the user info in req.user for other stuff later.

Does this classify as Token based auth?

I looked up online and read that instead of storing the token as a cookie on the client side, if I store the user info on the server side as session and a sessionid as a cookie on the client side, it classifies as Session based auth.

Thus clearly, my app has Token based auth right?

(I'm sorry if I'm seeking clarification for very basic stuff, I'm very much a beginner)

CodePudding user response:

Yes you have implemented the token based authentication in your scenario, session based is totally different thing on that approach you need to store session in your backend to track is client valid or not, but in token based you don't need to store sessions but you will have two tokens as ACCESS TOKEN and REFRESH TOKEN and need to store refresh token in database incase of future regeneration of access token that's how token based authentication works!

CodePudding user response:

You write that you "check if a token exists" and I assume this means that you look it up on a database. This is rather similar to an express-session, where the cookie contains a token and the session is also looked up on the database. The difference could be that you transport your token not in a cookie but in a request header (you don't say which technique you use).

However, one important aspect of token-based authorization is that the token need not be looked up on a database, but can be validated entirely in memory by verifying a signature. This is quicker and consumes fewer resources. Especially if your server receives many (malicious) requests with invalid tokens, it can detect and reject them without putting load on the database. See also the answer to Some questions about refresh tokens.

You could combine this with a session-based approach if the session ID also contains a signature and this is validated before the session is looked up on the database.

Read more about signed tokens and signature validation under the tag.

  • Related