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

@luvio/jwt-manager

v5.23.0

Published

Luvio Next generic JWT manager

Downloads

1,871

Readme

JWT Manager

JWT Manager is a package that simplifies the handling of JWT (JSON Web Tokens) in your application. It abstracts the process of retrieving, storing, and refreshing tokens with a clean and straightforward API.

Installation

You can add JWT Manager to your project using npm:

npm install @luvio/jwt-manager

Features

  • Get and refresh JWTs easily with getJwt and refreshToken methods.
  • Handle token expiration with automatic refresh.
  • Utilizes JwtRepository for token storage and management.
  • Works with a JwtResolver to retrieve tokens.
  • Allows additional extra info along with the token.

Usage

Here is a basic example of using JWT Manager in a Node.js application:

const { JwtManager, JwtRepository, JwtResolver } = require('@luvio/jwt-manager');

type EncodedJwtClaims = {
  exp: number;
  username: string;
}
type ExtraInfo = {
  envBaseUri: string;
}
// Your JwtResolver implementation
const jwtResolver: JwtResolver<ExtraInfo> = {
  getJwt(): Promise<{ jwt: string; extraInfo: ExtraInfo }> {
    return fetch(); // resolves the jwt.
  }
};

// Your JwtRepository implementation
const jwtRepository = new JwtRepository<EncodedJwtClaims, ExtraInfo>(
  3, // notifies that the token will expire in 3 seconds
  120, // if exp claim is not provided, the token will expire in 120 seconds.
);

// Create JwtManager instance
const jwtManager = new JwtManager(jwtRepository, jwtResolver);

// Get a JWT
jwtManager.getJwt().then((jwt) => {
  console.log(jwt.token);  // Prints the JWT
  console.log(jwt.decodedInfo);  // Prints the JWT decoded information
  console.log(jwt.extraInfo);  // Prints the JWT extra information
});

Remember that you will need to provide your own JwtResolver implementation of the JwtResolver interface. The JwtResolver should provide a getJwt method that retrieves a new JWT (and optionally extra info) when needed.

API Reference

The package exports two main elements: JwtManager class, JwtRepository class and JwtResolver and JwtToken types.

JwtManager

The JwtManager class is the main class in the JWT Manager package.

It exposes the following methods:

  • getJwt(): Returns a JWT. If a token request is in progress, it returns the Promise of this request. If the current token is undefined or expired, it initiates a token refresh. Otherwise, it returns the current token.
  • refreshToken(): Refreshes a JWT. If a refresh request is already in progress, it returns the Promise of this request. Otherwise, it starts a new refresh request and returns its Promise.

JWT Repository

The JwtRepository class is a storage and management solution for JWT (JSON Web Tokens) within the JWT Manager package.

The class handles:

  • Setting and getting the current JWT.
  • Notifying observers when the JWT is nearing its expiration.
  • Removing the JWT.

Usage

const { JwtRepository } = require('jwt-manager');

// Create JwtRepository instance with optional parameters
const jwtRepository = new JwtRepository(limitInSeconds, defaultTokenTTLInSeconds, logger);

// Set a JWT with optional extra information
jwtRepository.setToken('myJWT', { extra: 'info' });

// Get the current JWT
const currentToken = jwtRepository.token;

// Subscribe to the token nearing its expiration
const unsubscribe = jwtRepository.subscribeToTokenNearExpiration((token) => {
  console.log(`Token is about to expire: ${token}`);
});

// To unsubscribe
unsubscribe();

// Remove the current JWT
jwtRepository.removeToken();

API

JwtRepository exposes the following methods:

  • constructor(limitInSeconds: number, defaultTokenTTLInSeconds: number, logger: Logger): The constructor takes optional parameters to customize its behavior. The limitInSeconds sets the time before the token's expiry to notify observers. The defaultTokenTTLInSeconds sets the default token expiry time in seconds if "exp" claim is not present in the token. logger is used for logging warnings and errors.

  • token: Returns the current JWT.

  • setToken(token: string, extraInfo?: ExtraInfo): Sets the current JWT with optional extra information. Returns an object of the set token.

  • removeToken(): Removes the current JWT.

  • subscribeToTokenNearExpiration(cb: (token: JwtToken<T, ExtraInfo>) => void): Subscribes to the token nearing its expiration. It returns a function that can be used to unsubscribe.

JwtResolver

The JwtResolver type is used to define the structure for JWT resolver instances. It contains a getJwt method that should return a Promise with a JWT and optionally extra information.

Contributing

We welcome contributions! Please see our contributing guide for more details.

License

see the LICENSE.txt file for details.