Skip to content
Samuel S. Donovan edited this page Feb 2, 2022 · 13 revisions

express-auth is a simple, customizable authentication and authorization manager for express-based applications.

While express-auth provides default in-memory user, group, and session managers, these can easily be overridden with developer-provided interfaces.

Usage

Install

TODO: put on npm


npm install express-auth

Setup


const express = require('express');
const app = express();
const port = 80;

app.use(express.json()); //Not always needed

const cookieParser = require('cookie-parser');
app.use(cookieParser("secret"));

const auth = require('express-auth');
app.use(auth);

Simple Example


app.get('/', (req, res) => {
    if(req.user)
        res.send(`Logged in as ${req.user.id}`);
    else
        res.send(`Not logged in`);
});

Users & Groups


auth.users.add("John Doe", "password1234", {
    address: "1234 Main St.",
    phone: "(000)000-000"
});

auth.groups.new("example group", ["John Doe"]);

console.log(auth.users.get("John Doe");
console.log(auth.groups.with("John Doe");

Logging in/out


app.post('/login', (req, res) => {
    let username = req.body.username;
    let password = req.body.username;
    let loggedIn = auth.login(req, res, username, password);
    ...
});

app.post('/logout', (req, res) => {
    let loggedOut = auth.logout(req, res);
    ...
});

Restricting Access


app.use("/admin", auth.onlyUsers("admin"));

app.use("/manage-users", auth.onlyGroups("managers"));

Dependencies

express-auth is built specifically to be used with Express web framework for Node.js

Express is distributed under the Creative commons license.

express-auth uses cookies to track sessions, and cookie-parser makes this easier, as well as allow for the use of signed cookies.

cookie-parser is distributed under the MIT license.

express.json() (optional)

Used by the auth.login.endpoint for the username and password. Does not need to be used if auth.login.endpoint is never used.

This module is included with Express.

License

This work is licensed under a Creative Commons Attribution-ShareAlike 3.0 United States License.

Clone this wiki locally