Skip to content
Fetch middleware for OAuth2 support
Branch: master
Clone or download
Latest commit 7b3316c Mar 18, 2019
Permalink
Type Name Latest commit message Commit time
Failed to load latest commit information.
examples
src
.gitignore
.travis.yml
LICENSE
Makefile
README.md
changelog.md
package-lock.json
package.json
tsconfig.json
tslint.json
webpack.config.js

README.md

fetch-mw-oauth2

This library adds support to OAuth2 to fetch by wrapping the fetch function. It works both for fetch() in a browser, as well as node-fetch.

Installation

npm i fetch-mw-oauth2

Usage

The fetch-mw-oauth2 package effectively works as follows:

  1. You pass it OAuth2 instructions
  2. It returns an object with a new fetch() function.

This new fetch() function can now be used in place of the regular fetch, but it takes responsibility of oauth2 authentication.

Setup with access and/or refresh token

If you already have an access and/or refresh token obtained through other means, you can set up the object as such:

const OAuth2 = require('fetch-mw-oauth2');

const oauth2 = new OAuth2({
  clientId: '...',
  clientSecret: '...', // Optional in some cases
  accessToken: '...',
  refreshToken: '...',
  tokenEndPoint: 'https://auth.example.org/token',
});

const response = await oauth2.fetch('https://my-api.example.org/articles', {
  method: 'POST'.
  body: 'Hello world',
});

The fetch function simply calls the javascript fetch() function but adds an Authorization: Bearer ... header.

Setup via authorization_code grant

const OAuth2 = require('fetch-mw-oauth2');

const oauth2 = new OAuth2({
  grantType: 'authorization_code',
  clientId: '...',
  code: '...',
  tokenEndPoint: 'https://auth.example.org/token',
});

The library does not take responsibility for redirecting a user to an authorization endpoint and redirecting back. That's up to you. After that's done though, you should have a code variable that you can use to setup the OAuth2 object.

Setup via 'password' grant

const OAuth2 = require('fetch-mw-oauth2');

const oauth2 = new OAuth2({
  grantType: 'password',
  clientId: '...',
  clientSecret: '...',
  userName: '...',
  password: '...',
  tokenEndPoint: 'https://auth.example.org/token',
});

Setup via 'client_credentials' grant

const OAuth2 = require('fetch-mw-oauth2');

const oauth2 = new OAuth2({
  grantType: 'client_credentials',
  clientId: '...',
  clientSecret: '...',
  tokenEndPoint: 'https://auth.example.org/token',
});

Project status

The current features have been implemented:

  1. client_credentials grant-type support.
  2. password grant-type support.
  3. authorization_code grant-type support
  4. Automatically refreshing tokens

The following features are planned mid/long-term

  1. Supply an OAuth2 discovery document instead of authorization and token uris.
  2. implicit grant-type support
You can’t perform that action at this time.