Express middleware for easy OAuth with a variety of providers.

Overview

accounted4

NPMCBT badge

Express middleware for easy OAuth2 with a variety of providers.

accounted4 is intended to make it easy for developers to add third-party OAuth2! support to their Node.js applications. This project is still in its infancy; more features and providers will be added in the future. Supported OAuth2 providers are detailed below.

For more information on OAuth2, the folks at FusionAuth wrote a fantastic, easy-to-understand OAuth2 guide that I highly recommend. Additionally, the OAuth2 specification is a great resource for all other information about OAuth2.

Usage

Install the @tycrek/accounted4 package:

npm i @tycrek/accounted4

# You'll also need express-session and a session store. Optimally you'll use something other than MemoryStore in production.
npm i express-session memorystore

Preparing the code

accounted4 is intended for use with Express. It requires the use of express-session and a compatible session store. The easiest way to get started is by using the memorystore module. In a production environment, it is recommended to use a proper database with the corresponding module for a session store.

For tutorial purposes, this README will use memorystore, but feel free to use another if you prefer.

import { Accounted4 } from '@tycrek/accounted4';
import express from 'express';
import session from 'express-session';
import MemoryStore from 'memorystore';

const app = express();
const sessionStore = MemoryStore(session);

The next block attaches the session middleware to Express. You are recommended to adjust these settings as you see fit.

const DAY = 86400000;
app.use(session({
    name: 'accounted4',
    resave: true,
    saveUninitialized: false,
    cookie: { maxAge: DAY, secure: false /* set to true if using HTTPS*/ },
    secret: (Math.random() * 100).toString(),
    store: new sessionStore({ checkPeriod: DAY }) as any,
}));

This will initialize a session for each visitor to your app, which is accessible through req.session.

Configure a provider

For any provider you choose, you'll have to set up an "app" on the corresponding developer dashboard. See below for details on how to set this up for each provider.

Redirect URI's

Pretty much every provider requires a redirect URI. This is the URL that the provider will redirect to after the user has authenticated. To save some bytes, I'll just describe the redirect URI here, then you'll use it for all providers. If any providers use a different format, I'll note those differences in their subsection.

  • For local development: http://localhost:8080/accounted4/<provider-name>
  • For production: https://<your-domain.com>/accounted4/<provider-name>

Replace <provider-name> with the name of the provider, as listed below, in lowercase. You do not need a trailing slash. For example: https://awesome-website.com/accounted4/github or http://localhost:8080/accounted4/microsoft.

Providers

Discord

Create a Discord app. Once your app is created, click the OAuth2 tab and copy the Client ID and reset the Client Secret. Make sure you add both redirect URIs. Visit Discord's documentation for more information on scopes.

GitHub

Create a GitHub app. For the Authorization callback URL, use the production redirect URI. You do not need to enable Device Flow but you can if you want. Once created, find the Client ID and generate a new Client secret. Copy these for the next step. Visit GitHub's documentation for more information on scopes.

Google

Create a Google Cloud project. Using the search bar, start typing "APIs and Services", then select APIs & Services. Follow these steps to configure your app:

  1. On the left of the dashboard, select OAuth consent screen.
  2. Choose External and click Create.
  3. The next page sets up your app metadata. Enter anything required, but feel free to leave optional items blank.
  4. The next page asks for scopes. If you already know what scopes you require, enter them now. Otherwise, continue. Visit Google's documentation for more information on scopes.
  5. The next page asks for test users. Add yourself and any other Google account you wish to test your app. Make sure to enter the email address of any testers (the email must correspond to a Google account).
  6. If the summary looks good to you, click on Credentials on the left of the dashboard.
  7. Click on + Create credentials, then OAuth client ID.
  8. Choose Web application for the type and give it a name.
  9. Add both redirect URI's from above as Authorized redirect URIs (you don't need any Authorized JavaScript origins).
  10. Click Create. You will be shown your Client ID and Client secret. Copy these for the next step.
Microsoft

Microsoft is quite in-depth, so we'll skip the details here for now. Documentation will be added at a later date.

Spotify

Create a Spotify app (tutorial). Once your app is created, you should see your Client ID and a button to SHOW your Client secret. Copy these for the next step. Click on Edit Settings and add both redirect URI's. Visit Spotify's documentation for more information on scopes.

Twitch

Create a Twitch app (tutorial). Make sure to add both redirect URI's. Once your app is created, click Manage. Copy your Client ID and a button to make a New Secret. Copy these for the next step. Visit Twitch documentation for more information on scopes.


Configure accounted4

Finally, we create an instance of Accounted4. Passing the app is required as accounted4 needs to create routes for the OAuth2 provider to call upon for redirects. Support for more than one provider is planned for the future.

You can choose to apply the middleware to specific paths, or to the entire app.

const ac4 = new Accounted4(app, {
    hostname: 'localhost',
    port: 8080,
    defaultProvider: 'Microsoft',
    optionalProviders: ['GitHub'], // ! optionalProviders not yet implemented
    providerOptions: {
        Microsoft: {
            // Required by every provider
            clientId: secrets.MICROSOFT_CLIENT_ID,
            clientSecret: secrets.MICROSOFT_CLIENT_SECRET,

            // Optional for every provider (some have defaults)
            scopes: ['user.read', 'offline_access'], // You can add additional scopes

            // Optional for Microsoft (other providers may have other optional properties)
            tenant: 'consumers',
        },
        GitHub: {
            clientId: secrets.GITHUB_CLIENT_ID,
            clientSecret: secrets.GITHUB_CLIENT_SECRET,
        }
    }
});

app.use(ac4.auth());
// or
app.use('/my-private-zone', ac4.auth());

Now add the rest of your routes and start the app. Visiting any of your routes will redirect the user to the OAuth2 provider. Once they sign in, they'll be redirected back to your app.

Using the providers' API

After successful authentication, accounted4 stores the provider name and access token in the session. You can access these values through the req.session.accounted4 object. This access token can be used with the API of your chosen provider (make sure you include any necessary scopes when configuring the provider).

Next steps

At the moment, that's all there is to it! As development continues, I'll add more docs on usage.

List of providers

To-do

  • Add providers
  • Add documentation/tests/examples
  • Add support for multiple providers
  • Implement logout
  • Implement refreshing tokens
  • Automatic State checking

Disclaimer

accounted4 is set up for OAuth2 Authorization Code Grants. If your project requires a different grant, then this library may not be the right choice. Word of advice: never use implicit grant.

You might also like...

📋 Todo List CRUD and OAuth with Firebase

📋 Todo List CRUD and OAuth with Firebase

Todo List CRUD and OAuth with Firebase Esta es una app hecha con React y Firebase en la que puedas crear, leer, actualizar y borrar tareas dentro de u

May 28, 2022

Minimalistic pre-configured OAuth 2.0 client for Deno. Inspired by grant.

DenoGrant Minimalistic pre-configured OAuth 2.0 client for Deno. Inspired by Grant. NOTE: this is alpha software subject to breaking changes at anytim

Dec 13, 2022

A variety of jQuery plugin patterns for jump starting your plugin development

jQuery Plugin Patterns So, you've tried out jQuery Boilerplate or written a few of your own plugins before. They work to a degree and are readable, bu

Dec 31, 2022

converts nuggies to usd and usd to nuggies for a variety of restaurant chains. Also includes a rest api. Built using NextJS and TypeScript

Prices All prices are currently based on the 4-piece from the respective chain or the equivalent lowest amount of nuggies. Plan is to add multiple pri

Jan 14, 2022

The Raspberry Pi + OpenScan Pi Shield can be used to control two independent stepper motors and a variety of different cameras

OpenScan2 Overview: The Raspberry Pi + OpenScan Pi Shield can be used to control two independent stepper motors and a variety of different cameras (Pi

Jan 3, 2023

Service Installer for VMware Tanzu is a one-click automation solution that enables VMware field engineers to easily and rapidly install, configure, and operate VMware Tanzu services across a variety of cloud infrastructures.

Service Installer for VMware Tanzu Service Installer for VMware Tanzu seeks to provide a one-click automation solution to enable our VMware engineers

Dec 1, 2022

A docker container with a wide variety of tools for debugging and setting up micro-services

Frame One Software Placeholder There are numerous times during the dev ops deployments, that a placeholder container is needed. In the past, Frame One

May 29, 2022

A hub for web developers that offers a variety of tools to help with any developing needs.

A hub for web developers that offers a variety of tools to help with any developing needs.

WebDevHub - A place for developers WebDevHub is designed to be one central place for developers, that offers a variety of tools to help with any devel

Dec 11, 2022

microregex is an open source and highly curated catalog of regular expression patterns. It offers programmers RegEx snippets that can be quickly exported into a variety of programming languages and distributed around teams.

microregex is an open source and highly curated catalog of regular expression patterns. It offers programmers RegEx snippets that can be quickly exported into a variety of programming languages and distributed around teams.

microregex - A catalog of RegEx patterns View Demo · Report Bug · Request Feature Loved the tool? Please consider contributing ✍️ to help it improve!

Oct 25, 2022
Releases(v0.8.0)
  • v0.8.0(Oct 9, 2022)

  • v0.7.1(Oct 9, 2022)

  • v0.7.0(Oct 9, 2022)

    • fix: Discord wasn't using proper URL for refresh f9d1ee8
    • Added Digital Ocean as a provider 464410c

    https://github.com/tycrek/accounted4/compare/v0.6.3...v0.7.0

    Source code(tar.gz)
    Source code(zip)
  • v0.6.3(May 11, 2022)

    • Removed old imports 2e7f0cd
    • Added refreshing to some providers 899b077
    • Replaced "OAuth" with "OAuth2" in README d77893a
    • Added additional resource to README f8e98a1

    https://github.com/tycrek/accounted4/compare/v0.6.2...v0.6.3

    Source code(tar.gz)
    Source code(zip)
  • v0.6.2(May 11, 2022)

    • Updated all Provider implementations a917d1a
    • Added optional headers parameter bf268fb
    • Added info path to test; improved test error messages 6a33707
    • Improved error handling d111780
    • Implemented refresh 30849c0
    • Forgot this prop on Google c17c35d
    • Added refresh properties for future usage 0db4aa9
    • Added created property to ac4session 48cb3ac
    • Updated tests f400c4f

    https://github.com/tycrek/accounted4/compare/v0.6.1...v0.6.2

    Source code(tar.gz)
    Source code(zip)
  • v0.6.1(May 11, 2022)

    • Fix README formatting 5c8ab11
    • Added proper types to GitHub 696f11d
    • Added proper types (excluding scopes) to Microsoft provider 8d92934
    • Added proper types to Twitch provider 371d733
    • Added proper types to Spotify provider 4212b6b
    • Added proper types to Discord provider 920f195

    https://github.com/tycrek/accounted4/compare/v0.6.0...v0.6.1

    Source code(tar.gz)
    Source code(zip)
  • v0.6.0(May 8, 2022)

    Highlights: Twitch is now available as a provider! Also, rewrote most of the core code.

    • Added Twitch as a provider 16cdb0b
    • Updated README 1a12838
    • Rewrote tests for new code 0411686
    • Drastically improved configuration 3af426f
    • Added more docs f434da8
    • Finished providers list 0f85497

    https://github.com/tycrek/accounted4/compare/v0.5.0...v0.6.0

    Source code(tar.gz)
    Source code(zip)
  • v0.5.0(May 2, 2022)

    Highlight: Google is now available as a provider!

    • Improved README layout (and added Google to README) 8a812b1
    • Added Google as a provider 0e13166
    • Added more providers to list 369264f
    • Removed Apple from planned providers 6ef3c75

    https://github.com/tycrek/accounted4/compare/v0.4.0...v0.5.0

    Source code(tar.gz)
    Source code(zip)
  • v0.4.0(May 2, 2022)

    Highlight: GitHub is now available as a provider!

    • Updated .npmignore 099b2c7
    • Added note regarding redirect URI's 5337bb2
    • Added GitHub as a provider 60cab06
    • Maybe now? 40553e3
    • Added .gitattributes 16fb51f

    https://github.com/tycrek/accounted4/compare/v0.3.0...v0.4.0

    Source code(tar.gz)
    Source code(zip)
  • v0.3.0(May 1, 2022)

    Highlight: Microsoft is now available as a provider!

    • Updated README 96397d5
    • Added Spotify error handling 0169425
    • Added docs urls b16b8ac
    • Added Microsoft as a provider d330a67

    https://github.com/tycrek/accounted4/compare/v0.2.0...v0.3.0

    Source code(tar.gz)
    Source code(zip)
  • v0.2.0(May 1, 2022)

    Highlight: Spotify is now available as a provider!

    • Fixed scripts e60aef3
    • Added todo 27921ec
    • Updated README for Spotify docs a4a9c77
    • Added Spotify to testing db73760
    • 🎶 Added Spotify as a provider 0d91d50
    • Minor cleanup 069f7bf
    • Added redirectUri property; Removed /success from path f81f4c0
    • Updated README again 0591d36
    • Updated README 288bcc8

    https://github.com/tycrek/accounted4/compare/v0.1.3...v0.2.0

    Source code(tar.gz)
    Source code(zip)
  • v0.1.3(Apr 30, 2022)

  • v0.1.1(Apr 30, 2022)

  • v0.1.0(Apr 30, 2022)

    • Added .npmignore 9d27b9f
    • Added test file ee964a5
    • Initial source dump a672046
    • Set up NPM 1829dbc
    • Updated .gitignore 8e237c2
    • Fixed description 8e1e1b1

    https://github.com/tycrek/accounted4/compare/427399f6dfc24e1309af34ae4d18d2a9141c472c...v0.1.0

    Source code(tar.gz)
    Source code(zip)
Owner
Josh Moore
Java dev, full-stack web dev, and privacy advocate.
Josh Moore
Hemsida för personer i Sverige som kan och vill erbjuda boende till människor på flykt

Getting Started with Create React App This project was bootstrapped with Create React App. Available Scripts In the project directory, you can run: np

null 4 May 3, 2022
Kurs-repo för kursen Webbserver och Databaser

Webbserver och databaser This repository is meant for CME students to access exercises and codealongs that happen throughout the course. I hope you wi

null 14 Jan 3, 2023
startupDB is an Express middleware function implementing a high-performance in-memory database

startupDB startupDB is a database designed to create REST APIs. It is implemented as an Express middleware function and allows for easy implementation

Jeroen de Vries 8 Jul 26, 2022
express-like middleware system for your remix loaders and actions

remix-middleware Add an express-like middleware stack to your remix loaders and actions! yarn add remix-middleware // ./app/middleware.server.ts expor

Eric Bower 26 Nov 22, 2022
🤖 An action that fetches the list of malicious domains on Discord in different providers and creates/updates a JSON file with them from time to time.

Discord Guardian Action ??  This action fetches the list of malicious domains on Discord in different providers and creates/updates a JSON file with t

Dalton Menezes 7 Nov 30, 2022
The best Nodejs price kit you need when working with cryptocurrencies with multiple providers support

Cryptocurrency Price Kit STAGE: RFC The best Nodejs price kit you need when working with cryptocurrencies with multiple providers support. Goal To pro

TrapCode 6 Sep 7, 2022
📬 A quick comparison of private and / or secure email providers

?? Email Comparison A comparison table of private and / or secure email providers Live App The app can be accessed at: lissy93.github.io/email-compari

Alicia Sykes 47 Dec 15, 2022
A flexible gateway for running ML inference jobs through cloud providers or your own GPU. Powered by Replicate and Cloudflare Workers.

Cogflare (Working title) Cogflare is a Cloudflare Workers application that aims to simplify running distributed ML inference jobs through a central AP

NightmareBot 14 Dec 12, 2022
Remix Auth plugin for Twitter OAuth 1.0a

Remix Auth Twitter Remix Auth plugin for Twitter OAuth 1.0a. Supported runtimes Runtime Has Support Node.js ✅ Cloudflare ✅ Demo Try out live demo (sou

na2hiro 13 Dec 31, 2022
OAuth 2 / OpenID Connect Client for Web API runtimes

OAuth 2 / OpenID Connect Client for Web APIs runtime This is a collection of bits and pieces upon which a more streamlined Client module may be writte

Filip Skokan 187 Jan 6, 2023