πŸ” Session-Based vs. Token-Based Authentication: Which is better?πŸ€” (2024)

Fidal Mathew

Posted on

πŸ” Session-Based vs. Token-Based Authentication: Which is better?πŸ€” (3) πŸ” Session-Based vs. Token-Based Authentication: Which is better?πŸ€” (4) πŸ” Session-Based vs. Token-Based Authentication: Which is better?πŸ€” (5) πŸ” Session-Based vs. Token-Based Authentication: Which is better?πŸ€” (6) πŸ” Session-Based vs. Token-Based Authentication: Which is better?πŸ€” (7)

#webdev #beginners #node #javascript

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.

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 setupapp.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 }}));

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'); }});

Protected route

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

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 } });});

πŸ” 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, },})

9. 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.

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 }); } });});

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 middlewarefunction 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'); }}

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)

Subscribe

notachraf

notachraf

grug no dev, grug small brain

  • Work

    Ovrsea

  • Joined

β€’ Dec 23 '23

  • Copy link

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 )

Fidal Mathew

Fidal Mathew

MERN stack developer | web3 developer | Freelance Technical writer |Hackathons X 3πŸ†

  • Email

  • Location

    New Delhi, India

  • Education

    VIT, Chennai

  • Work

    Ex Technical Content Writer @Aviyel; @Codedamn| Ex Frontend Developer Intern @SimpliClariFy

  • Joined

β€’ Dec 24 '23

  • Copy link

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

Thomas Broyer

Thomas Broyer

Developer and architect mainly interested in web development (frontend, Web APIs), web app security, build tools, Java, Kotlin, Gradle, etc.

  • Location

    Dijon, France

  • Joined

β€’ Dec 23 '23

  • Copy link

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")

Fidal Mathew

Fidal Mathew

MERN stack developer | web3 developer | Freelance Technical writer |Hackathons X 3πŸ†

  • Email

  • Location

    New Delhi, India

  • Education

    VIT, Chennai

  • Work

    Ex Technical Content Writer @Aviyel; @Codedamn| Ex Frontend Developer Intern @SimpliClariFy

  • Joined

β€’ Dec 23 '23

  • Copy link

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.

Thomas Broyer

Thomas Broyer

Developer and architect mainly interested in web development (frontend, Web APIs), web app security, build tools, Java, Kotlin, Gradle, etc.

  • Location

    Dijon, France

  • Joined

β€’ Dec 23 '23

  • Copy link

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)

Fidal Mathew

Fidal Mathew

MERN stack developer | web3 developer | Freelance Technical writer |Hackathons X 3πŸ†

  • Email

  • Location

    New Delhi, India

  • Education

    VIT, Chennai

  • Work

    Ex Technical Content Writer @Aviyel; @Codedamn| Ex Frontend Developer Intern @SimpliClariFy

  • Joined

β€’ Dec 23 '23

  • Copy link

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...

Thomas Broyer

Thomas Broyer

Developer and architect mainly interested in web development (frontend, Web APIs), web app security, build tools, Java, Kotlin, Gradle, etc.

  • Location

    Dijon, France

  • Joined

β€’ Dec 24 '23

  • Copy link

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!

Sadiq Salau

Sadiq Salau

A fullstack developer with a passion for coding and problem solving, constantly looking for ways to expand his knowledge.

  • Location

    Nigeria

  • Joined

β€’ Dec 23 '23

  • Copy link

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..

Atomic Code

Atomic Code

  • Joined

β€’ Apr 25

  • Copy link

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.****

hoosayn

hoosayn

  • Joined

β€’ Dec 26 '23

  • Copy link

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?

Thomas Broyer

Thomas Broyer

Developer and architect mainly interested in web development (frontend, Web APIs), web app security, build tools, Java, Kotlin, Gradle, etc.

  • Location

    Dijon, France

  • Joined

β€’ Dec 26 '23

  • Copy link

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)

Sadiq Salau

Sadiq Salau

A fullstack developer with a passion for coding and problem solving, constantly looking for ways to expand his knowledge.

  • Location

    Nigeria

  • Joined

β€’ Dec 23 '23

  • Copy link

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...

Fidal Mathew

Fidal Mathew

MERN stack developer | web3 developer | Freelance Technical writer |Hackathons X 3πŸ†

  • Email

  • Location

    New Delhi, India

  • Education

    VIT, Chennai

  • Work

    Ex Technical Content Writer @Aviyel; @Codedamn| Ex Frontend Developer Intern @SimpliClariFy

  • Joined

β€’ Dec 24 '23

  • Copy link

One of the disadvantages of token-based authentication.

Jackson Kasi

Jackson Kasi

I am not only interested in developing applications, and also I am interested in Business, Marketing, Stocks, Art...

  • Email

  • Location

    India

  • Education

    Completed School, no College but Learner until Death 😎

  • Work

    I am try to be an entrepreneur 🎯

  • Joined

β€’ Apr 23

  • Copy link

The backend language for my project is TypeScript.

ABIDULLAH786

ABIDULLAH786

πŸ‘¨β€πŸ’» Passionate Developer | βš›οΈ React.js/Next.js Lover | 🌐 MERN Stack Aficionado | 🌱 Lifelong Learner | πŸ’‘ Sharing Insights | πŸš€ Let's Code, Collaborate, and Create Amazing Web Experiences!

  • Email

  • Location

    Sukkur, Sindh

  • Education

    BS in Computer Science

  • Joined

β€’ Dec 24 '23

  • Copy link

Very useful...

Fidal Mathew

Fidal Mathew

MERN stack developer | web3 developer | Freelance Technical writer |Hackathons X 3πŸ†

  • Email

  • Location

    New Delhi, India

  • Education

    VIT, Chennai

  • Work

    Ex Technical Content Writer @Aviyel; @Codedamn| Ex Frontend Developer Intern @SimpliClariFy

  • Joined

β€’ Dec 25 '23

  • Copy link

Thank you!!

Darryl Ruggles

Darryl Ruggles

Cloud Solutions Architect @ Ciena

  • Location

    Ottawa, ON, Canada

  • Education

    Acadia University

  • Work

    Cloud Solutions Architect @ Ciena

  • Joined

β€’ Dec 23 '23

  • Copy link

Very well explained! Thanks for your time on this!

Fidal Mathew

Fidal Mathew

MERN stack developer | web3 developer | Freelance Technical writer |Hackathons X 3πŸ†

  • Email

  • Location

    New Delhi, India

  • Education

    VIT, Chennai

  • Work

    Ex Technical Content Writer @Aviyel; @Codedamn| Ex Frontend Developer Intern @SimpliClariFy

  • Joined

β€’ Dec 24 '23

  • Copy link

Glad that you liked it! 😊

Ian Macartney

Ian Macartney

friendly engineer. works at convex.dev

  • Location

    San Francisco, CA

  • Joined

β€’ Apr 25

  • Copy link

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...

Noor Ahmed

Noor Ahmed

A humble person. Sometimes I am lost, Sometimes happy, some

  • Education

    BUITEMS

  • Work

    Full Stack Engineer at RepairDesk

  • Joined

β€’ Dec 25 '23

  • Copy link

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

Fidal Mathew

Fidal Mathew

MERN stack developer | web3 developer | Freelance Technical writer |Hackathons X 3πŸ†

  • Email

  • Location

    New Delhi, India

  • Education

    VIT, Chennai

  • Work

    Ex Technical Content Writer @Aviyel; @Codedamn| Ex Frontend Developer Intern @SimpliClariFy

  • Joined

β€’ Dec 25 '23

  • Copy link

Thank you! Means a lot! 😁

prod42

prod42

everything about real world production manufacturing software

  • Joined

β€’ Dec 23 '23

  • Copy link

Exceptionally good explanation. On the point.

Fidal Mathew

Fidal Mathew

MERN stack developer | web3 developer | Freelance Technical writer |Hackathons X 3πŸ†

  • Email

  • Location

    New Delhi, India

  • Education

    VIT, Chennai

  • Work

    Ex Technical Content Writer @Aviyel; @Codedamn| Ex Frontend Developer Intern @SimpliClariFy

  • Joined

β€’ Dec 23 '23

  • Copy link

Thank you!! Glad that you liked it! 😁

hoosayn

hoosayn

  • Joined

β€’ Dec 26 '23

  • Copy link

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?

Joes

Joes

  • Joined

β€’ Aug 31

  • Copy link

not bad βœ…

Joes

Joes

  • Joined

β€’ Aug 31

  • Copy link

not badβœ…

View full discussion (26 comments)

For further actions, you may consider blocking this person and/or reporting abuse

πŸ” Session-Based vs. Token-Based Authentication: Which is better?πŸ€” (2024)
Top Articles
Buy 1 Oz Gold Bars
What to Eat After a Run: 15 Great Choices
Spectrum Gdvr-2007
Walgreens Harry Edgemoor
Foxy Roxxie Coomer
Matgyn
Skycurve Replacement Mat
Online Reading Resources for Students & Teachers | Raz-Kids
Crossed Eyes (Strabismus): Symptoms, Causes, and Diagnosis
When is streaming illegal? What you need to know about pirated content
Otis Department Of Corrections
Best Transmission Service Margate
His Lost Lycan Luna Chapter 5
Craigslist Phoenix Cars By Owner Only
Cvs Devoted Catalog
Tiraj Bòlèt Florida Soir
Which Is A Popular Southern Hemisphere Destination Microsoft Rewards
Dityship
2016 Hyundai Sonata Refrigerant Capacity
Craigslist In Visalia California
Missed Connections Inland Empire
Wics News Springfield Il
Rapv Springfield Ma
Obituaries Milwaukee Journal Sentinel
Dove Cremation Services Topeka Ks
Klsports Complex Belmont Photos
Urbfsdreamgirl
Wolfwalkers 123Movies
Biografie - Geertjan Lassche
Umn Biology
Mississippi Craigslist
Ehome America Coupon Code
Christmas Days Away
Lincoln Financial Field, section 110, row 4, home of Philadelphia Eagles, Temple Owls, page 1
Gus Floribama Shore Drugs
Asian Grocery Williamsburg Va
Retire Early Wsbtv.com Free Book
Sephora Planet Hollywood
In Polen und Tschechien droht Hochwasser - Brandenburg beobachtet Lage
Property Skipper Bermuda
Tsbarbiespanishxxl
Craigs List Hartford
Exploring the Digital Marketplace: A Guide to Craigslist Miami
Watch Chainsaw Man English Sub/Dub online Free on HiAnime.to
844 386 9815
Laura Houston Wbap
Ewwwww Gif
10 Bedroom Airbnb Kissimmee Fl
Strawberry Lake Nd Cabins For Sale
Tanger Outlets Sevierville Directory Map
Peugeot-dealer Hedin Automotive: alles onder één dak | Hedin
Latest Posts
Article information

Author: Corie Satterfield

Last Updated:

Views: 6437

Rating: 4.1 / 5 (42 voted)

Reviews: 81% of readers found this page helpful

Author information

Name: Corie Satterfield

Birthday: 1992-08-19

Address: 850 Benjamin Bridge, Dickinsonchester, CO 68572-0542

Phone: +26813599986666

Job: Sales Manager

Hobby: Table tennis, Soapmaking, Flower arranging, amateur radio, Rock climbing, scrapbook, Horseback riding

Introduction: My name is Corie Satterfield, I am a fancy, perfect, spotless, quaint, fantastic, funny, lucky person who loves writing and wants to share my knowledge and understanding with you.