@luvio/jwt-manager
v5.23.0
Published
Luvio Next generic JWT manager
Downloads
1,871
Maintainers
Keywords
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
andrefreshToken
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. ThelimitInSeconds
sets the time before the token's expiry to notify observers. ThedefaultTokenTTLInSeconds
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.