@authelion/api-utils 🛡
The main propose of this package, is to provide general utilities for authorization & authentication.
Table of Contents
Installation
npm install @authelion/api-utils --save
Usage
KeyPair
The following context parameters are all optional and will inherit default values,
if not otherwise specified.
import {
DSAKeyPairOptions,
ECKeyPairOptions,
RSAKeyPairOptions,
RSAPSSKeyPairOptions,
} from 'crypto';
type KeyPairContext = {
type: 'rsa' | 'rsa-pss' | 'dsa' | 'ec',
options?: RSAKeyPairOptions<'pem', 'pem'> |
RSAPSSKeyPairOptions<'pem', 'pem'> |
DSAKeyPairOptions<'pem' | 'pem'> |
ECKeyPairOptions<'pem', 'pem'>,
directory?: string,
privateName?: string,
privateExtension?: string,
publicName?: string,
publicExtension?: string,
passphrase?: string,
save?: boolean
}
The useKeyPair
method will
- create a key-pair, if it does not already exist
- use an internal runtime cache, if the key was once loaded before during runtime
import path from 'path';
import {
useKeyPair,
KeyPairContext
} from "@authelion/server";
const context: KeyPairContext = {
directory: path.join(__dirname, 'writable'),
}
(async () => {
const keyPair = await useKeyPair(context);
console.log(keyPair);
})();
Sign & Verify
The signToken
and verifyToken
provide a simple way to sign and verify a token (default: RS256
).
A private- & public-key will be automatically generated if none already exists.
import path from 'path';
import {
KeyPairContext,
signToken,
verifyToken
} from "@authelion/api-utils";
const keyPair: KeyPairContext = {
directory: path.join(__dirname, 'writable')
}
(async () => {
const token : Record<string, any> = {foo: 'bar'};
const tokenSigned = await signToken(token, {
options: {
expiresIn: 3600
},
keyPair
});
const tokenVerified = await verifyToken(tokenSigned);
console.log(tokenVerified);
})();
Hash
To simply hash and verify a password with the password hashing-function bcrypt based on the Blowfish cipher,
use the methods hash
& compare
.
import {
hash,
compare
} from "@authelion/api-utils";
(async () => {
const hashed = await hash('start123', 10);
let isValid = await compare('start123', hashed);
console.log(isValid);
isValid = await compare('star1234', hashed);
console.log(isValid);
})();