npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

cognito-toolkit

v1.0.5

Published

Helpers for AWS Cognito to build web applications with authentication/authorization

Downloads

817

Readme

cognito-toolkit NPM version

Helpers to authenticate and authorized users using AWS Cognito user pools. A JWT token (either an id or access token) is validated and returned in a decrypted form. Simple helpers are provided to make decisions on accessibility of API endpoints for a given user.

Examples

const makeGetUser = require('cognito-toolkit');

// run getUser() on every request
const getUser = makeGetUser({
  region: 'us-east-1',
  userPoolId: 'us-east-1_MY_USER_POOL'
});

// ...somewhere in our endpoint we have a context variable: ctx

const authHeader = ctx.headers.authorization;
const authCookie = ctx.cookies.get('auth');

const user = getUser(authHeader || authCookie);

if (user) {
  console.log('Our user:\r\n' + JSON.stringify(user, null, 2));
} else {
  console.log('User was not authenticated.');
}

How to install

npm install --save cognito-toolkit
# yarn add cognito-toolkit

Documentation

All provided functions are explained below. See the examples above for usage patterns.

makeGetUser(options)

This is the main function directly returned from the main module. It returns an asynchronous function, which is used to decode a user.

It takes one argument options, which is an object with the following properties or an array of such objects:

  • region &mdash required string, which specifies an AWS region, such as 'us-east-1'. Default: none.
  • userPoolId &mdash required string, which specifies a user pool ID, such as 'us-east-1_MY_USER_POOL'. Default: none.

The returned function takes a token as a string (possible sources are a header or a cookie) and returns a decoded JWT token or null (cannot positively authenticate).

Utilities: utils/lazyAccessToken

It is a helper to retrieve an access token lazily on demand.

setCredentials(url, clientId, secret)

This synchronous function sets credentials for future authentications. It takes a URL (usually in the form of Cognito user pool DNS/oauth2/token), an app client ID and an app client secret (all as strings) and retrieves an access token (see TOKEN Endpoint, the part on client_credentials).

getToken()

This synchronous function returns the current token whatever it is. If it was not retrieved yet, it will return null.

authorize()

This asynchronous function checks if there is an unexpired token and retrieves it, if required. It uses credentials set by setCredentials() (see above). As a result it returns a token or null, if credentials were not set. After running this function the current token can be obtained with getToken() (see above).

Examples:

const {setCredentials, authorize} = require('cognito-toolkit/utils/lazyAccessToken');

// ...

setCredentials(
  'https://auth.my-custom-domain/oauth2/token',
  process.env.AUTH_CLIENT_ID,
  process.env.AUTH_CLIENT_SECRET
);

// ...

const doIt = async () => {
  // every time we call it, it retrieves a token from a server
  const token = await authorize();
  // use the token immediately: it can be changed next time you need it
  const options = {
    protocol: 'https',
    hostname: 'api.my-custom-domain.com',
    path: '/items',
    method: 'GET',
    headers: {
      Accept: 'application/json',
      Authorization: token.access_token
    }
  };
  // do a call ...
};

Utilities: utils/renewableAccessToken

It is a helper to retrieve an access token on demand, then renew it by a timer automatically.

retrieveToken(url, clientId, secret)

This asynchronous function takes a URL (usually in the form of Cognito user pool DNS/oauth2/token), an app client ID and an app client secret (all as strings) and retrieves an access token (see TOKEN Endpoint, the part on client_credentials).

Warning: the function always uses https protocol, which is a default for Cognito pools.

The function schedules itself to run when a token is about to expire. The exact algorithm is expires_in (defined in the token structure) minus 5 minutes. If the result is negative, it will run in a half of expires_in time.

While the function resolves its return in a token structure, do not save it because it can be updated over time. Always use getToken() function (described below) before using a token.

Example:

const {retrieveToken} = require('cognito-toolkit/utils/renewableAccessToken');

// ...

const doIt = async () => {
  // every time we call it, it retrieves a token from a server
  const token = await retrieveToken(
    'https://auth.my-custom-domain/oauth2/token',
    process.env.AUTH_CLIENT_ID,
    process.env.AUTH_CLIENT_SECRET
  );
  // use the token immediately: it can be changed next time you need it
  const options = {
    protocol: 'https',
    hostname: 'api.my-custom-domain.com',
    path: '/items',
    method: 'GET',
    headers: {
      Accept: 'application/json',
      Authorization: token.access_token
    }
  };
  // do a call ...
};

getToken()

This synchronous function returns the current token whatever it is. If it was not retrieved yet, it will return null.

Example:

// rewriting the previous example

const {retrieveToken, getToken} = require('cognito-toolkit/utils/renewableAccessToken');

const authorize = () => {
  // this function can be called multiple times
  // it calls the retrieveToken() only when necessary
  // and getToken() always returns the fresh token
  if (!getToken()) {
    return retrieveToken(
      'https://auth.my-custom-domain/oauth2/token',
      process.env.AUTH_CLIENT_ID,
      process.env.AUTH_CLIENT_SECRET
    );
  }
};

// ...

const doIt = async () => {
  await authorize(); // we can call it many times without taxing the auth system
  const token = getToken(); // totally safe to get a token like that
  // like in the previous example ...
};

Versions

  • 1.0.5 Updated dependencies.
  • 1.0.4 Updated dependencies.
  • 1.0.3 Updated dependencies.
  • 1.0.2 Updated dependencies.
  • 1.0.1 Added support for multiple pools.
  • 1.0.0 The initial public release.

License

The 3-Clause BSD License