Common Authentication Methods: HTTP Basic, Session‑Cookie, Token, and OAuth
This article reviews four widely used authentication mechanisms—HTTP Basic Authentication, session‑cookie, token‑based verification (including JWT), and OAuth—explaining their workflows, security characteristics, implementation details with Node.js/Express code samples, and comparative advantages for different application scenarios.
During a recent front‑end refactor the author replaced a session‑cookie scheme with token authentication and decided to summarize the most common authentication methods.
1. HTTP Basic Authentication
This is the simplest method defined by the HTTP protocol. The client requests a resource, the server responds with 401 Unauthorized and a WWW-Authenticate: Basic realm="..." header, prompting the browser to show a login dialog. The user’s credentials are Base64‑encoded and sent back in the Authorization: Basic … header. The server decodes the header, verifies the username and password against its user store, and returns the requested resource if the check succeeds.
GET /index.html HTTP/1.0
Host: www.google.com HTTP/1.0 401 Unauthorized
WWW-Authenticate: Basic realm="google.com"
Content-Type: text/html
Content-Length: xxx GET /index.html HTTP/1.0
Host: www.google.com
Authorization: Basic d2FuZzp3YW5nThe Base64 string d2FuZzp3YW5n represents the user name and password concatenated with a colon.
2. Session‑Cookie Authentication
The server creates a session object on the first request, stores it (commonly in Redis), and returns a unique session identifier (SID) in a Set‑Cookie header. The browser stores the SID and automatically includes it in subsequent requests. The server looks up the SID, retrieves the associated session data, and determines whether the request is authenticated.
var express = require('express');
var RedisStore = require('connect-redis')(express.session);
var app = express();
var secret = "wang839305939";
app.use(express.cookieParser(secret));
app.use(express.session({
store: new RedisStore({host: "127.0.0.1", port: 6379, db: "session_db"}),
secret: secret
}));
app.get("/", function(req, res) {
var session = req.session;
session.time = session.time || 0;
var n = session.time++;
res.send('hello, session id:' + session.id + ' count:' + n);
});
app.listen(9080);3. Token Verification (JWT example)
After a successful login the server issues a token (often a JWT) that encodes user information and an expiration time. The client stores the token (e.g., in localStorage or a cookie) and includes it in the Authorization header of every subsequent request. The server validates the token’s signature and expiry before granting access.
{
"alg": "HS256",
"typ": "JWT"
} {
"sub": "1234567890",
"name": "John Doe",
"admin": true
} HMACSHA256(
base64UrlEncode(Headers) + "." +
base64UrlEncode(Claims),
SECRET_KEY
) let jwt = require('jwt-simple');
let secret = "wangyy";
let time = 10;
module.exports = {
validate: function(req, res, next) {
let token = req.body.token || req.headers["xssToken"];
if (token) {
let decodeToken = null;
try { decodeToken = jwt.decode(token, secret, 'HS256'); }
catch (err) { res.status(401).send("非法访问"); return; }
let exp = decodeToken.exp;
if (!exp) { res.status(401).send("非法访问"); return; }
let now = new Date().getTime();
if (exp > (now + time * 60 * 1000)) {
res.send({code:'002', errorMsg:"授权超时"});
}
next();
} else {
res.status(401).send("非法访问");
}
},
makeToken: function() {
let payload = {time: new Date().getTime(), exp: this.makeExp(time)};
return jwt.encode(payload, secret, HS256);
},
makeExp: function(time) { let stam = time*60000; }
}; let express = require('express');
let app = express();
let bodyParser = require('body-parser');
let auth = require('./lib/auth.js');
app.use(bodyParser.json());
app.post('/login', function(req, res, next) {
let Token = auth.makeToken();
res.json({result:"success", token:Token}, 200);
});
app.use('*',[auth.validate], function(req, res, next) {
res.send('success');
});
app.listen('9999');4. OAuth (Open Authorization)
OAuth is an open standard that lets users grant third‑party applications limited access to their resources without sharing passwords. The typical flow (OAuth 2.0) includes: user authorizes the client, the authorization server returns an authorization code , the client exchanges the code for an Access Token , and finally the client uses the token to call protected APIs.
https://graph.qq.com/oauth2.0/show?which=Login&display=pc&response_type=code&client_id=100270989&redirect_uri=https%3A%2F%2Fpassport.csdn.net%2Faccount%2Flogin%3Foauth_provider%3DQQProvider&state=testKey parameters in the OAuth request URL include response_type , client_id , redirect_uri , oauth_provider , and state . After the user authorizes, the server redirects to the supplied redirect_uri with a code parameter, which the client then exchanges (along with client_id , client_secret , and redirect_uri ) for an Access Token . The token is finally presented to the resource server to obtain the protected data.
In summary, the choice of authentication method depends on the product’s security requirements and target audience: simple internal tools may use HTTP Basic or session‑cookie, while public‑facing services benefit from token‑based schemes or OAuth for better user experience and broader client support.
Architect
Professional architect sharing high‑quality architecture insights. Topics include high‑availability, high‑performance, high‑stability architectures, big data, machine learning, Java, system and distributed architecture, AI, and practical large‑scale architecture case studies. Open to ideas‑driven architects who enjoy sharing and learning.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.