How Modern Authentication Works OAuth, JWT, and Sessions Explained
Introduction
Every secure website needs a way to verify who its users are. This process is called authentication. Over the years, authentication methods have evolved from simple username and password systems to more advanced approaches like OAuth and JWT. Understanding these concepts is essential for modern web developers.
This blog breaks down how authentication works, compares different methods, and shows real code examples that you can apply in your projects.
What is Authentication
Authentication is the process of confirming a user’s identity before allowing access to protected parts of an application. Common examples include logging into a website, mobile app, or online dashboard.
A basic authentication flow usually involves
- User enters credentials
- Server verifies them
- If valid, user gets access
- If invalid, access is denied
Traditional Session Based Authentication
How it works
In session based authentication, the server creates a session for the user after login and stores it in memory or a database. A session ID is sent to the user in a cookie.
Each request then includes this cookie so the server can recognize the user.
Example login flow with sessions in Node.js Express
const express = require("express");
const session = require("express-session");
const app = express();
app.use(session({
secret: "mySecretKey",
resave: false,
saveUninitialized: true
}));
app.post("/login", (req, res) => {
const { username, password } = req.body;
if (username === "admin" && password === "1234") {
req.session.user = username;
res.send("Login successful");
} else {
res.send("Invalid credentials");
}
});
app.get("/dashboard", (req, res) => {
if (req.session.user) {
res.send("Welcome to your dashboard");
} else {
res.send("Please log in first");
}
});
app.listen(3000);
Pros and Cons of Sessions
Pros
- Easy to implement
- Good for traditional web apps
- Works well with cookies
Cons
- Requires server memory or database storage
- Harder to scale for large applications
What is JWT Authentication
JWT stands for JSON Web Token. Instead of storing user data on the server, the server creates a signed token and sends it to the client.
The client stores this token, usually in local storage, and sends it with every request.
Example of creating a JWT in Node.js
const jwt = require("jsonwebtoken");
const token = jwt.sign(
{ user: "admin" },
"secretKey",
{ expiresIn: "1h" }
);
console.log(token);
Example of verifying a JWT
jwt.verify(token, "secretKey", (err, decoded) => {
if (err) {
console.log("Invalid token");
} else {
console.log("User:", decoded.user);
}
});
Pros and Cons of JWT
Pros
- Stateless, no need to store sessions on server
- Works well for APIs and mobile apps
- Easy to scale
Cons
- Token can be stolen if not stored securely
- Cannot easily invalidate tokens before expiration
What is OAuth
OAuth is an authorization framework that allows users to log in using third party providers like Google, GitHub, or Facebook.
Instead of creating a new account, users can sign in using an existing account.
Simple OAuth login flow
- User clicks Login with Google
- Website redirects user to Google
- User approves access
- Google sends a token back to the website
- Website uses token to get user information
Example using Google OAuth in Node.js
const passport = require("passport");
const GoogleStrategy = require("passport-google-oauth20").Strategy;
passport.use(new GoogleStrategy({
clientID: "YOUR_GOOGLE_CLIENT_ID",
clientSecret: "YOUR_GOOGLE_CLIENT_SECRET",
callbackURL: "/auth/google/callback"
},
function(accessToken, refreshToken, profile, done) {
return done(null, profile);
}));
When to use OAuth
Use OAuth when
- You want social login
- You do not want to manage passwords
- You need third party authentication
Comparing Authentication Methods
Session based
- Best for traditional websites
- Simple and secure with cookies
JWT based
- Best for APIs and mobile apps
- Scalable and stateless
OAuth
- Best for social login
- Reduces password management
Best Practices for Secure Authentication
- Always use HTTPS
- Hash passwords using bcrypt
- Never store plain text passwords
- Set JWT expiration times
- Use secure cookies for sessions
- Enable two factor authentication
Conclusion
Modern authentication methods like sessions, JWT, and OAuth each have their own strengths. Choosing the right one depends on your application type, scalability needs, and security requirements. By understanding these systems and using them correctly, you can build secure and user friendly web applications.