create-express-auth-middleware
Library to easily create Express JS authentication and authorization middlewares using predicate functions.
Installation
npm install create-express-auth-middleware
Example
View samples folder for more specific examples
-
Make a API call from client, and include an Authorization header, e.g.
Authorization: Bearer <your-client-token>
-
If an API call is made with a valid token, you can access the decoded token object from request
const app = require("express")();
const { create_authn_middleware, create_authz_middleware } = require("create-express-auth-middleware");
app.use(create_authn_middleware((req) => req.get("Authorization") === "some_JWT_Value"));
app.get(
"/data/:userID",
create_authz_middleware((req) => decodeJWT(req.get("Authorization")).userID === req.params.userID),
create_authz_middleware((req) => isNotRateLimited(req) || { status: 429, error: "Too many requests" }),
(req, res) => res.status(200).json({ data: "Protected user data" })
);
-
If authentication failed, you get a 401 code with the following response by default
{ "ok": false, "error": "Authentication Failed" }
-
If authorization failed, you get a 403 code with the following response by default
{ "ok": false, "error": "Authorization Failed" }
The only difference between authentication middlewares and authorization middlewares is their error HTTP status codes and their default error responses as shown above.
Using with Auth providers
Instead of building your own authentication and authorization backend, you can use auth providers like Firebase Auth, Okta, Auth0 to provide auth services and just use this library to create authentication and authorization middlewares built on top of their API.
Integrations available
License and Author
This project is made available under MIT LICENSE and written by JJ