Common Authentication Methods: HTTP Basic, Session‑Cookie, Token, and OAuth
This article reviews four widely used authentication mechanisms—HTTP Basic authentication, session‑cookie based authentication, token (JWT) authentication, and OAuth 2.0—explaining their workflows, security characteristics, and providing Node.js/Express code examples for each.
Recently, while refactoring a company's front‑end code, I switched from session‑cookie authentication to token authentication and decided to organize several common authentication methods.
1. HTTP Basic Authentication
Basic authentication is defined by the HTTP protocol; the server challenges the client with a 401 response containing a WWW-Authenticate: Basic realm="..." header. The client then prompts the user for credentials, encodes "username:password" with Base64, and resends the request with an Authorization: Basic ... header. The server decodes the header and validates the credentials against its user store.
Process
Get /index.html HTTP/1.0
Host:www.google.comServer replies:
HTTP/1.0 401 Unauthorized
WWW-Authenticate: Basic realm="google.com"
...After the user enters credentials, the client sends:
Get /index.html HTTP/1.0
Host:www.google.com
Authorization: Basic d2FuZzp3YW5nNode.js example (Express) that implements the challenge and validation:
let express = require("express");
let app = express();
app.use(express.static(__dirname + '/public'));
app.get("/Authentication_base", function(req, res) {
console.log('req.headers.authorization:', req.headers);
if (!req.headers.authorization) {
res.set({'WWW-Authenticate': 'Basic realm="wang"'});
res.status(401).end();
} else {
let base64 = req.headers.authorization.split(" ")[1];
let userPass = new Buffer(base64, 'base64').toString().split(":");
let user = userPass[0];
let pass = userPass[1];
if (user == "wang" && pass == "wang") {
res.end("OK");
} else {
res.status(401).end();
}
}
});
app.listen(9090);Corresponding index.html that triggers the request:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>HTTP Basic Authentication</title>
</head>
<body>
<div></div>
<script src="js/jquery-3.2.1.js"></script>
<script>
$(function(){
send('./Authentication_base');
});
var send = function(url){
$.ajax({
url: url,
method: 'GET',
});
}
</script>
</body>
</html>2. Session‑Cookie
Session‑cookie authentication relies on a server‑side session object identified by a unique session ID (sid) stored in a cookie on the client. The workflow includes creating the session, optionally signing the sid, sending the sid in a Set‑Cookie header, and on subsequent requests the server retrieves the session using the sid to determine whether the request is authenticated.
3. Token Authentication
After a successful login, the server issues a token (often a JWT) that the client stores (cookie, localStorage, etc.) and includes in the Authorization header of every subsequent request. The server validates the token's signature and expiration; if valid, the request is processed, otherwise a 401 response is returned.
JWT structure: Header (alg, typ), Claims (payload), Signature (HMACSHA256 of Base64‑encoded header and claims). Example token:
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9....
Node.js example using jwt-simple to generate and validate tokens:
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){
return time*60000 + new Date().getTime();
}
};Express server that issues a token on /login and protects all other routes:
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){
let Token = auth.makeToken();
res.json({result:"success", token:Token}, 200);
});
app.use('*', [auth.validate], function(req, res){
res.send('success');
});
app.listen('9999');4. OAuth (Open Authorization)
OAuth is an open standard that allows a user to grant a third‑party application limited access to resources hosted by another service provider without sharing credentials. The typical OAuth 2.0 flow includes: (1) user authorizes the client, (2) authorization server returns a code, (3) client exchanges the code for an access_token, and (4) the client uses the access token to call protected APIs.
Key parameters in the authorization request URL: response_type, client_id, redirect_uri, state, etc.
Summary
Different authentication mechanisms suit different scenarios. For internal systems, simple session or token solutions may suffice. For public‑facing applications, OAuth provides a better user experience and reduces credential exposure.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Top Architect
Top Architect focuses on sharing practical architecture knowledge, covering enterprise, system, website, large‑scale distributed, and high‑availability architectures, plus architecture adjustments using internet technologies. We welcome idea‑driven, sharing‑oriented architects to exchange and learn together.
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.
