DEV Community

Cover image for ๐Ÿ” Session-Based vs. Token-Based Authentication: Which is better?๐Ÿค”
Fidal Mathew
Fidal Mathew

Posted on

๐Ÿ” Session-Based vs. Token-Based Authentication: Which is better?๐Ÿค”

Hi fellow readers!โœ‹ I hope youโ€™re doing great. In this article, we will learn about session and token-based authentication methods used in backend applications. Letโ€™s take a look at them.

๐Ÿ” Session-based auth

In simple words, session-based authentication uses a special code(session id) stored on your device to remember who you are when you visit a website, keeping you logged in and remembering your information until you leave or log out. Didnโ€™t get it? Donโ€™t worry, letโ€™s take a look step by step.

1. User Login:

Users log in by sending their email and password to the server through a special request.

2. Checking Details:

The server checks if the provided details match what's stored for the user.

3. Creating a Session:

If everything is correct, the server makes a 'session' that holds user info (like user ID, permissions, and time limits). This info is kept safe in the server's storage. Exam or can also be managed using libraries such as express-session.

4. Getting a Session ID:

The server sends this 'session ID' back to the user's device, usually as a cookie in the response.

5. Using the Session ID:

Whenever the user wants something from the server, their device automatically includes this session ID in its requests.

6. Server Checks:

The server uses this session ID to find the stored information about the session user in the session storage.

Hereโ€™s a sneak peek at how express-session works:

  • When the user logs in, the server creates a session for that user and sets a cookie๐Ÿช in the response containing the session ID.

  • The browser automatically includes this session ID cookie๐Ÿช in subsequent requests to the server.

  • When the server receives a request, express-session middleware uses the session ID from the cookie๐Ÿช to retrieve the relevant session data.

  • The data stored in req.session (such as userId) becomes available to handle the request.

7. Access Granted:

If everything matches up, the server knows the user is genuine and responds to them with access to what they asked for.

Session auth working

Example

Here's an example of a Node.js application using Express.js to implement session authentication.

Implementation



const express = require('express');
const session = require('express-session');

const app = express();

// Middleware setup
app.use(session({
secret: 'your_secret_key',
resave: false,
saveUninitialized: false,
cookie: {
httpOnly: true, // Set the cookie as HTTP-only, Optional
maxAge: 60*30 // In secs, Optional
}
}));

Enter fullscreen mode Exit fullscreen mode




Login route




app.post('/login', (req, res) => {
const { username, password } = req.body;
const user = users.find(u => u.username === username && u.password === password);

if (user) {
req.session.userId = user.id; // Store user ID in session
res.send('Login successful');
} else {
res.status(401).send('Invalid credentials');
}
});

Enter fullscreen mode Exit fullscreen mode




Protected route




app.get('/home', (req, res) => {
if (req.session.userId) {
// User is authenticated
res.send(Welcome to the Home page, User </span><span class="p">${</span><span class="nx">req</span><span class="p">.</span><span class="nx">session</span><span class="p">.</span><span class="nx">userId</span><span class="p">}</span><span class="s2">!);
} else {
// User is not authenticated
res.status(401).send('Unauthorized');
}
});

Enter fullscreen mode Exit fullscreen mode




Logout route




app.get('/logout', (req, res) => {
req.session.destroy(err => {
if (err) {
res.status(500).send('Error logging out');
} else {
res.redirect('/'); // Redirect to the home page after logout
}
});
});

Enter fullscreen mode Exit fullscreen mode




๐Ÿ” Token-based auth

JWT authentication uses digitally signed tokens containing user information to allow secure and verified access to websites or applications without needing to repeatedly log in. Letโ€™s take a look at the step-by-step workflow of token-based authentication.

1. User Login Request:

Users log in by sending their email and password to the server through a specific request.

2. Credential Verification:

The server verifies the provided credentials against the stored user data.

3. Token Generation:

Upon successful verification, the server creates a token (commonly JWT - JSON Web Token). This token holds user information (claims) such as user_id, permissions.

4. Token Signing and Hashing:

The token is signed with a secret key and processed with a hashing algorithm (like SHA256) to create a hash.

5. Sending the Token:

The server sends this token to the client, which stores it, typically in the browser.

6. Token Storage Options:

The client can store the token in different ways like HttpOnly Cookies, Session Storage, or Local Storage. Storing in HttpOnly Cookies is recommended as it prevents JavaScript access, enhancing security against XSS attacks.

7. Token Expiry and Security:

Tokens often have an expiration time to enhance security.

8. Including Token in Requests:

For every request to the server, the client sends the token in the Authorization header.

It's a good practice to prefix the token with "Bearer ".



axios.get(URL, {
headers: {
'Authorization': 'Bearer ' + token,
},
})

Enter fullscreen mode Exit fullscreen mode



  1. Server-Side Validation:

Upon receiving a request, the server retrieves the token.

10. Token Validation and User Authentication:

Using the secret key, the server validates the token and extracts claims from it. If the user information from the claims exists in the server's user table, the server authenticates the user, granting access to requested resources.

Token based authentication

Example

Login



app.post('/login', (req, res) => {

const { username, password } = req.body;
const user = users.find(u => u.username === username && u.password === password);

jwt.sign({ user }, secretKey, { expiresIn: '1h' }, (err, token) => {
if (err) {
res.status(500).send('Error generating token');
} else {
res.json({ token });
}
});
});

Enter fullscreen mode Exit fullscreen mode




Protected route

We are using veriyToken() function as middleware for every route that needs verification. The request passes through the veriyToken() and only if the next() function is called, it passes on to this route and implements the code.



app.get('/dashboard', verifyToken, (req, res) => {
res.send('Welcome to the Home page');
});

// Verify token middleware
function verifyToken(req, res, next) {
const token = req.headers['authorization'];

if (typeof token !== 'undefined') {
jwt.verify(token.split(' ')[1], secretKey, (err, decoded) => {
if (err) {
res.status(403).send('Invalid token');
} else {
req.user = decoded.user;
next();
}
});
} else {
res.status(401).send('Unauthorized');
}
}

Enter fullscreen mode Exit fullscreen mode




Key differences

  • Storage Location: Sessions are stored on the server, while tokens (JWTs) are stored on the client side.

  • Stateful vs Stateless: Sessions are stateful, while tokens are stateless, allowing for better scalability in distributed systems.

  • Expiry Handling: Session expiry is managed by the server, whereas token expiry is handled by the token itself.

  • Security Measures: JWTs often include digital signatures and support for encryption, enhancing security compared to typical session mechanisms that use cookies, and can be vulnerable to CSRF attacks if not properly protected.

  • Usage Flexibility: Tokens (JWTs) offer more flexibility in carrying additional information beyond authentication, useful for authorization and custom data transmission.

Which method should be used?

It depends upon the requirement and nature of the application. Most applications use a hybrid approach, token-based authentication for APIs, and session-based authentication for web-based interactions.

I hope you liked this article and if you did donโ€™t forget to give it a like! Which backend language do you use for your projects? ๐Ÿค”

Comment them down below ๐Ÿ‘‡

Connect with me on-

Top comments (26)

Collapse
 
notachraf profile image
notachraf

Honestly in the era of OAuth2, SSO, password-less.... JWT's are the way to go, but session id still have a lot of uses.

Also, in the beginning of projects, I try to abstract those concerns as they are never a core business decision in the beginning, so I just use a framework ( like NextAuth ) and only deal with authorization ( not authentication )

Collapse
 
fidalmathew profile image
Fidal Mathew

That's a great point. Authorization frameworks do make the job easy for us. Thanks for sharing your insights!

Collapse
 
tbroyer profile image
Thomas Broyer

How does one log out? That's a major difference between them. Put differently, how does one revoke a token? If you have to check the token against a database of revoked tokens, how's that different from a session?

BTW, we're talking about self-sufficient tokens here, but other kinds of token exist that are just the same as session IDs, just sent differently (cookie vs "something else")

Collapse
 
fidalmathew profile image
Fidal Mathew

We can log out in token-based authentication by deleting the token stored in the browser (local/session/cookie storage). It is done in the frontend whereas if a session needs to be destroyed the command is executed in the server code.

Collapse
 
tbroyer profile image
Thomas Broyer

Forgetting something or just stopping using it yourself has zero security value. So technically you cannot logout with a self-sufficient token, you cannot revoke it, unless you start making it stateful.

TL;DR: don't use such tokens, at least not that way.

(fwiw, I've written about this recently; unfortunately I'm on mobile right now so can't easily find the links; you'll find them in my DEV profile)

Thread Thread
 
fidalmathew profile image
Fidal Mathew

The article is amazing!
I'll put it out here for others to check it out as well. @tbroyer has pointed out some great points about the compromises we make while developing authorization.
Check it out: dev.to/tbroyer/beyond-the-login-pa...

Thread Thread
 
tbroyer profile image
Thomas Broyer

Thanks for the kind words ๐Ÿค—

The other article I wanted to point out was dev.to/tbroyer/what-are-jwt-nm0 about what JWT are best used for (spoiler: not any kind of "session"). And please don't take my word for it, go read the articles referenced at the end!

Collapse
 
sadiqsalau profile image
Sadiq Salau

Use cookies If you want to store authentication data on the client side.. You still need to append the token to every request you make, that's not different from a cookie..

Collapse
 
atomiccode profile image
Atomic Code

You probably do not want to check the JWT against the database because it's not even designed for that. JWT eliminates the need to have any kind of state, be it in the database or on the server as a session. The JWT has an expiration date, and you should set an expiration 100% of the time.

But the problem then comes, how do you revoke access? The answer is - you don't, so keep the expiration time near.

The next question is, how do I stop the user from automatically getting logged out once expired? The answer is - by using a refresh token that is stored in the database close to the expiration of the JWT. That way, you only need to check the database every 15 minutes or so.

If you want fast middleware that doesn't eat up RAM on your server and is not dependent on a specific server, use JWT.

If you want a way to log someone out by the split second, use sessions. But each user shouldn't use different servers at the same time, and you need to make sure the sessions are removed from memory after use in some lower languages.****

Collapse
 
hoosayn profile image
hoosayn

Recently I developed a project based on token authentication. To keep the state I store the token in db and match for every subsequent request after authentication of the first request. Is this good approach or what could be the draw backs?

Collapse
 
tbroyer profile image
Thomas Broyer

If you didn't mean your token to be self-contained, then it's totally ok and definitely the way to go! (and more or less what an http session in any web framework gives you, the only difference being how the token or session I'd is sent over the wire).

The "problem" is choosing a self-sufficient token format so it's "stateless", and then realizing you can't revoke said tokens, so shoehorning some state, defeating the whole reason you chose self-sufficient tokens in the first place.
I'm not saying it cannot be done efficiently, keeping some perf advantage over "stateful tokens", but it also becomes more complex.

However if you used tokens to authenticate a first-party web frontend to its backend, my opinion is you should just use cookie-based sessions instead. CSRF are a solved problems nowadays so there's no drawback to using cookies, and on the server you have plenty of libraries/frameworks to implement it with pluggable storage mechanisms (make sure you only ever store the user identity in the session though, and otherwise be stateless)

Collapse
 
jacksonkasi profile image
Jackson Kasi

The backend language for my project is TypeScript.

Collapse
 
sadiqsalau profile image
Sadiq Salau

If the server can't revoke a token at anytime it wants then it's bad. A minute is enough for an attacker if they acquire your JWT token...

Collapse
 
fidalmathew profile image
Fidal Mathew

One of the disadvantages of token-based authentication.

Collapse
 
rdarrylr profile image
Darryl Ruggles

Very well explained! Thanks for your time on this!

Collapse
 
fidalmathew profile image
Fidal Mathew

Glad that you liked it! ๐Ÿ˜Š

Collapse
 
ianmacartney profile image
Ian Macartney

Redis put out this free e-book about why JWTs are not safe for sessions. Worth a read, esp if you care about the logout problem: redis.io/resources/json-web-tokens...

Collapse
 
abidullah786 profile image
ABIDULLAH786

Very useful...

Collapse
 
fidalmathew profile image
Fidal Mathew

Thank you!!

Collapse
 
noorcs profile image
Noor Ahmed

I really love the simplicity of your explanation. It really helps.

Collapse
 
fidalmathew profile image
Fidal Mathew

Thank you! Means a lot! ๐Ÿ˜

Collapse
 
prod42net profile image
prod42

Exceptionally good explanation. On the point.

Collapse
 
fidalmathew profile image
Fidal Mathew

Thank you!! Glad that you liked it! ๐Ÿ˜

Collapse
 
hoosayn profile image
hoosayn

Recently I developed a project based on token authentication. To keep the state I store the token in db and match for every subsequent request after authentication of the first request. Is this good approach or what could be the draw backs?