@vinka/karhu v2.2.0
Http Client for Secured APIs
Introduction
Karhu is a wrapper around axios library to make it easier to consume JWT protected APIs.
The library will first get the access token from the authentication backend (auth0 or azure)
using client id and client secret and then include that token in every request made to
the API in Authorization
header.
For example:
Authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsImtpZCI6....
Currently supported authentication backends:
- Auth0
- Azure AD
Installation
npm install @vinka/karhu
Caching Tokens
Karhu caches tokens on disk for faster access. This is useful when used in scripts, not so much when used in backend services because those tend to be long running and the token will remain in memory anyway.
By default, Karhu will always write the bearer token on disk in file ~/.vinka-tokens.json
. You can override
this location with options
. If you want to disable the tokenfile completely, provide tokenFile: null
in
options
. Loading the token from disk is not done automatically but must be explicitly calling the
loadToken()
function. This should be done right after instantiation.
For example:
const bear = new Bear({host: 'http://foo.bar', authMode: 'azure'});
await bear.loadToken();
To disable token caching:
const bear = new Bear({
host: 'http://foo.bar',
authMode: 'azure',
tokenFile: null,
});
Options
All config options:
interface BearOptions {
host: string;
authMode: 'azure' | 'auth0';
tokenEndpoint?: string;
clientId?: string;
clientSecret?: string;
audience?: string;
scope?: string;
log?: Log;
tokenFile?: string | null;
}
Example usage
Auth0
import * as bear from '@vinka/karhu';
const client: bear.Bear = new bear.Bear({
host: 'https://api.mycompany.com',
authMode: 'auth0',
log: console,
tokenEndpoint: 'https://mytenant.eu.auth0.com/oauth/token',
clientId: 'U01kjJWPIexcDrS5tdHbRGbPeKZ3Xaod',
clientSecret: 'XEh51wCnF00Bt2Xd1SbSm6FZ4CZ_TG_JVCB3aVC9tscqajTO-xzs-42kh2Nqfx2p',
audience: 'https://api.somecompany.com/audience',
});
(async () => {
await client.loadToken(); // optional, but will speed things up
const myorderstatus = await client.get('/order/323/status');
})()
Azure AD
import * as bear from '@vinka/karhu';
const client: bear.Bear = new bear.Bear({
host: 'https://api.mycompany.com',
authMode: 'azure',
log: console,
tokenEndpoint: 'https://login.microsoftonline.com/mytenantid-012c-4241-991d-2199618c5c5a/oauth2/v2.0/token/',
clientId: 'b22bf26c-5d0b-336b-be32-3f0d360f7g11',
clientSecret: 'b.Jz2kw2w]bP3XujJyK_3ze8MnEtzFm[',
scope: 'api://b3e88e2d-1cxe-4cb5-11df-d6d2j119ea26/.default',
});
(async () => {
await client.loadToken(); // optional, but will speed things up
const myorderstatus = await client.get('/order/323/status');
})()