AI summary
Add an SMS one-time code after password login in ExpressA web framework for Node.js. You map URLs to functions that answer the requests. with Twilio VerifyTwilio's API for one-time codes. Twilio is a company that sends SMS messages and phone calls through its API.: send it, check it, protect routes and add rate limits.
- You don't generate or store the code. Twilio VerifyTwilio's API for one-time codes. Twilio is a company that sends SMS messages and phone calls through its API. generates, sends and checks it.
- Checking a code that has expired or was already used returns a 404, and you have to catch it.
- SMS costs money. Add your own rate limits on top of Twilio's.
A correct password doesn’t tell you the person typing it owns the phone on the account. A one-time code over SMS (OTPOne-time password: a short code that works for a single login and expires after a few minutes.) adds that second check.
You don’t have to build much for it. Twilio VerifyTwilio's API for one-time codes. Twilio is a company that sends SMS messages and phone calls through its API. generates the code, sends it and checks it. Twilio keeps a record of each code it sends, called a verification. A verification is pending until the user types the right code, and then it’s approved.
Your app stores one flag, verified, in the session. The session is the data the server holds for one logged-in browser, and a cookie tells the server which session belongs to which browser. Your app also handles Twilio’s answers and limits how many SMS messages people can trigger, because you pay for each one.
I built this in 2022 as a small demo with ExpressA web framework for Node.js. You map URLs to functions that answer the requests., EJSA template engine for Express: it fills HTML pages with data on the server., MongoDBA document database. The demo stores its users in it., PassportA login library for Express. Its passport-local plugin checks an email and password, then puts the logged-in user on req.user. and Twilio VerifyTwilio's API for one-time codes. Twilio is a company that sends SMS messages and phone calls through its API.. That demo used the library versions of that time. I’ve rewritten the pieces below for today’s Twilio SDKA company's official library for calling its API from your code. Here it's the twilio package on npm., ExpressA web framework for Node.js. You map URLs to functions that answer the requests. 5, MongooseA Node.js library for MongoDB. You define models such as User and query them with methods like findById. and PassportA login library for Express. Its passport-local plugin checks an email and password, then puts the logged-in user on req.user., so they don’t match the 2022 code line for line.
- Password check
passport-local finds the user by email and compares the password with bcrypt.
- Half a session
The session exists, but verified is false. The user can reach /users/verify, not the dashboard.
req.session.verified = false - SMS sent
Twilio generates and sends the code. The verification starts as pending.
verifications.create({ to, channel: 'sms' }) - Code entry
The user types the code from the SMS into the form. It's valid for 10 minutes by default.
- Code check
The server asks Twilio about the code. If it's right, the status comes back approved.
verificationChecks.create({ to, code }) - Full session
The session gets flagged and the protected routes open up.
req.session.verified = true
Sending and checking the code
In the Twilio ConsoleTwilio's web dashboard, where you create services and see your logs., create a Verify Service. You need only one, not one per code. It holds the settings your codes go out with, such as the name shown in the SMS. Put its SIDTwilio's ID for a resource, such as your Verify Service. Each kind starts with its own two letters., the one starting with VA, in your .env.
Each verification stays open for 10 minutes by default. After that, its code no longer works.
Twilio’s current examples authenticate with an API key. Store phone numbers in E.164The international phone number format: a plus sign, the country code, then the number, with no spaces. format (+1...). In the demo I used intl-tel-inputA JavaScript library for phone number fields. It adds a country picker and gives you the number in E.164 format. on the signup form for that.
// config/twilio.js
const twilio = require("twilio");
const client = twilio(process.env.TWILIO_API_KEY, process.env.TWILIO_API_SECRET, {
accountSid: process.env.TWILIO_ACCOUNT_SID,
});
const verify = client.verify.v2.services(process.env.TWILIO_VERIFY_SERVICE_SID);
function sendCode(phone) {
return verify.verifications.create({ to: phone, channel: "sms" });
}
async function checkCode(phone, code) {
try {
const check = await verify.verificationChecks.create({ to: phone, code });
return check.status === "approved" ? "approved" : "wrong";
} catch (err) {
if (err.status === 404) return "expired";
if (err.code === 60202) return "locked";
throw err;
}
}
module.exports = { sendCode, checkCode };The catch block matters. My first version, on ExpressA web framework for Node.js. You map URLs to functions that answer the requests. 4, didn’t catch Twilio’s errors. An expired code comes back as a 404, which the SDKA company's official library for calling its API from your code. Here it's the twilio package on npm. throws as an error. With nothing to catch it, Node’s default settings stop the whole process.
Protecting the routes
The app uses four middleware functions: isLoggedIn, isVerified, notLoggedIn and notVerified. Middleware is a function ExpressA web framework for Node.js. You map URLs to functions that answer the requests. runs before a routeA URL path plus the function that answers it, such as POST /users/verify.’s own handler. Each one either calls next() to move on or answers the request itself, here with a redirect.
isLoggedIn checks the password step and isVerified checks the code step. notLoggedIn and notVerified do the opposite. Put isLoggedIn and isVerified on every routeA URL path plus the function that answers it, such as POST /users/verify. you want to protect. The code below shows the first two.
// config/middleware.js
const isLoggedIn = (req, res, next) =>
req.user ? next() : res.redirect("/users/login");
const isVerified = (req, res, next) =>
req.session.verified ? next() : res.redirect("/users/verify");// routes/user.js
const messages = {
wrong: "That code is wrong.",
expired: "That code has expired. Request a new one.",
locked: "Too many attempts. Wait a bit and try again.",
};
router.post(
"/login",
notLoggedIn,
loginLimiter,
passport.authenticate("local", {
failureRedirect: "/users/login",
failureFlash: true,
}),
async (req, res) => {
// Passport has already regenerated the session at this point.
req.session.verified = false;
await sendCode(req.user.phonenumber);
res.redirect("/users/verify");
},
);
router.post("/verify", isLoggedIn, notVerified, verifyLimiter, async (req, res) => {
const result = await checkCode(req.user.phonenumber, req.body.verifyCode);
if (result === "approved") {
req.session.verified = true;
return res.redirect("/users/dashboard");
}
req.flash("error_msg", messages[result]);
res.redirect("/users/verify");
});
router.post("/resend", isLoggedIn, notVerified, resendLimiter, async (req, res) => {
await sendCode(req.user.phonenumber);
res.redirect("/users/verify");
});
router.get("/dashboard", isLoggedIn, isVerified, (req, res) => {
res.render("dashboard");
});In the demo, resend was a GET link. I’ve made it a POST, because a GET that sends an SMS can be triggered by a link preview or a request from another site.
In ExpressA web framework for Node.js. You map URLs to functions that answer the requests. 5, errors in async handlers reach the error middleware on their own. That’s the middleware ExpressA web framework for Node.js. You map URLs to functions that answer the requests. calls when a handler fails. On ExpressA web framework for Node.js. You map URLs to functions that answer the requests. 4 you’d need try/catch and next(err).
Rate limits and SMS pumping
Twilio protects a single number on its own: 5 checks per verification and a cap on repeated sends.
Resending within the 10 minutes delivers the same code. Twilio recommends at most one send per 30 seconds per number, and the resend limit below uses the same window.
None of those limits help if someone feeds your app a long list of different numbers. Every SMS still lands on your bill. The numbers belong to the attacker or their partners, who get a cut of what the mobile carriers charge for each SMS. That attack is called SMS pumping, so add rate limitsA cap on how many requests someone can make in a time window. Past it, the server answers with HTTP 429 instead of doing the work. of your own:
const { rateLimit } = require("express-rate-limit");
const perUser = (windowMs, limit) =>
rateLimit({
windowMs,
limit,
keyGenerator: (req) => req.user.id,
standardHeaders: "draft-8",
legacyHeaders: false,
});
const loginLimiter = rateLimit({ windowMs: 15 * 60_000, limit: 10 });
const resendLimiter = perUser(30_000, 1);
const verifyLimiter = perUser(60_000, 5);Those numbers are a starting point, so tune them to your traffic.
By default the limiter keeps its counts in the server’s memory. If you run more than one server, each one counts on its own, so move the counts to a shared store like RedisAn in-memory database that several servers can share. It's often used for counters and sessions..
There are three settings on Twilio’s side too. The first is Service Rate Limits, where you define a key and a bucket.
The key is what Twilio counts by, such as the user’s IP address, and you choose its name. The bucket is how many sends that key gets in a time window.
If you named the key end_user_ip_address, you pass rateLimits: { end_user_ip_address: req.ip } when sending. req.ip is the visitor’s IP address as ExpressA web framework for Node.js. You map URLs to functions that answer the requests. sees it.
The other two are quick: turn on SMS Fraud GuardA Twilio setting that blocks SMS messages to number ranges Twilio has seen used for SMS pumping., and use Geo Permissions to switch off countries where you have no users.
Before going live
The demo skipped most of this:
- Session store:
express-session’s defaultMemoryStoreleaks memory and only works in a single process. Keep sessions in a database instead, for example RedisAn in-memory database that several servers can share. It's often used for counters and sessions. or MongoDBA document database. The demo stores its users in it., through a store package such asconnect-redisorconnect-mongo. - Cookies: Keep
httpOnlyon so page scripts can’t read the session cookie;express-sessionsets it by default. SetsameSite: "lax"yourself, so the browser leaves the cookie off most requests that other sites start. In production, also setsecure, so the cookie only goes over HTTPS. - Proxies: In production the app often sits behind a proxy, such as nginx or a load balancer, that receives each request first and passes it on. Add
app.set("trust proxy", 1)so ExpressA web framework for Node.js. You map URLs to functions that answer the requests. reads the visitor’s address and HTTPS status from the proxy’s headers. Without it, the secure cookie won’t be set andreq.ipwill be the proxy’s address. - CSRF: The forms POST and rely on the session cookie, so another site could make a logged-in user’s browser submit them. That attack is called CSRF. Add a CSRF token, a random value your own forms send and other sites can’t know.
- Passwords: Hash with bcryptA password hashing function that is slow on purpose, so guessing passwords from a stolen hash takes a long time. and put
if (!this.isModified("password")) return;in thepre("save")hook, which MongooseA Node.js library for MongoDB. You define models such as User and query them with methods like findById. runs before it saves a user, or each save hashes the hash. - Signup: Don’t hand
req.bodystraight toUser.create, because a user can post extra fields you never meant to accept. Pick the fields one by one. - If you update older code like the 2022 demo: MongooseA Node.js library for MongoDB. You define models such as User and query them with methods like findById. 7 dropped the
findByIdcallback, so useawaitindeserializeUser, the PassportA login library for Express. Its passport-local plugin checks an email and password, then puts the logged-in user on req.user. function that loads the user from the session on each request. ExpressA web framework for Node.js. You map URLs to functions that answer the requests. 5 removedres.redirect("back"), so usereq.get("Referrer") || "/".
If MongoDBA document database. The demo stores its users in it. runs on the same server, don’t expose its port. Securing MongoDB with UFW shows how to close it with Ubuntu’s firewall.
If your app runs on Next.jsA React framework that also runs code on the server. with NextAuth.jsA login library for Next.js, now also called Auth.js., why jwt.verify can’t read its session token covers how to read the session instead.
References
- Twilio Verify API
- Twilio Verification Check resource
- Twilio Verify developer best practices
- Twilio Verify Service Rate Limits
- Twilio Verify rate limits and timeouts
- Twilio guidance on SMS pumping and toll fraud
- Express security best practices
- express-session documentation
- Passport changelog
- Migrating to Express 5
- Migrating to Mongoose 7
- express-rate-limit configuration
