lets-mfa-express
v0.1.89
Published
LetsMFA bindings for ExpressJS
Downloads
185
Readme
#Lets MFA Express Bindings
A simple way to add MFA to your Express app.
Use Case
Use this library to add MFA protection to your Express app. This library will add the necessary routes to your Express app to handle the MFA flow. It will also add a middleware to your app that will check for a valid id_token on the request. If the id_token is not valid, the middleware will allow you to redirect the user.
Installation
npm install --save lets-mfa-express
Generate Keys
Before you can use the library, you must generate a public/private key pair. This can be done with the following command. The keys will be written to the current directory. The private key is a secret and should be stored securely.
npx lets-mfa-express generate-keys
Usage
The following is a simple example of how to use the library. This will add MFA protection for the coveredPaths
.
const express = require("express");
const app = express();
const letsMfa = require("lets-mfa-express");
const { existsSync, readFileSync } = require("fs");
// Read the keys from the file system
// Better yet, you should store these in a secrets manager
const publicKeyPath = "public-key.json";
const privateKeyPath = "private-key.json";
if (!existsSync(publicKeyPath) || !existsSync(privateKeyPath))
throw new Error("Must generate keys first");
const keys = {
publicKey: readFileSync(publicKeyPath).toString(),
privateKey: readFileSync(privateKeyPath).toString(),
};
// This adds LetsMFA bindings to your express server
// It should be called before any other routes are added
new LetsMFAExpress(app, {
// The paths that will be protected by MFA
coveredPaths: ["/protected"],
// The domain for the user account
domain: "example.com",
// The base URL for your express app
// The hostname must be part of the domain above
baseUrl: RESPONSE_URL_BASE,
// The keys from above
keys: {
publicKey: keys.publicKey,
privateKey: keys.privateKey,
},
// The URL to the logo that will be displayed on the MFA page
logoUrl: "http://localhost:4000/static/logo.png",
// Called after successful authentication
authResponseHandler: async (req, res, response) => {
// Get the User object from the database by username
let user = getUserFromDB(response.sub);
// Update the user's "accountVault" with the response
user.accountVault = response.accountVault;
// Save the user back to the database
saveUserToDB(user);
// Send the user to wherever they need to go after completing MFA
res.redirect(301, "/");
},
// Called when a user visits a 'coveredPath' without having
// a valid LetsMFA id_token
invalidAccessHandler: async ({
req,
res,
next,
client,
idTokens,
validation,
}) => {
// If the user is not authenticated, respond or redirect
// the user appropriately
res.status(401).send("Not Authorized");
},
});