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;
}
const jwtResolver: JwtResolver<ExtraInfo> = {
getJwt(): Promise<{ jwt: string; extraInfo: ExtraInfo }> {
return fetch();
}
};
const jwtRepository = new JwtRepository<EncodedJwtClaims, ExtraInfo>(
3,
120,
);
const jwtManager = new JwtManager(jwtRepository, jwtResolver);
jwtManager.getJwt().then((jwt) => {
console.log(jwt.token);
console.log(jwt.decodedInfo);
console.log(jwt.extraInfo);
});
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');
const jwtRepository = new JwtRepository(limitInSeconds, defaultTokenTTLInSeconds, logger);
jwtRepository.setToken('myJWT', { extra: 'info' });
const currentToken = jwtRepository.token;
const unsubscribe = jwtRepository.subscribeToTokenNearExpiration((token) => {
console.log(`Token is about to expire: ${token}`);
});
unsubscribe();
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.