A very simple oauth2 Node.js client for use with the Client Credentials flow based upon simple-oauth2.
By calling the http() method the user is able to have an axios instance returned with the oauth2 headers pre-defined.
Please be aware this this is almost exclusively designed for my personal requirements doesn't necessarily (easily) support advanced features of these libraries.
Install the library using npm:
npm install https://github.com/aaronheath/basic-oauth2.git
Install the library using yarn:
yarn add https://github.com/aaronheath/basic-oauth2.git
Basic oauth supports the following configuration file structure.
{
"client": {
"id": "client-id",
"secret": "client-secret"
},
"auth": {
"tokenHost": "host domain (https://example.com)"
},
"tls": {
"validate": bool (optional)
}
}
By default the configuration should be placed in a file named .oauth-config.json
in the root directory of the project.
However, an option argument can be supplied ot the oauthToken()
method (as displayed below), which represents the name of the project / service.
Where supplied, this name will be included this name will be expected within the configuration files name.
Example (code example in Example of Usage section):
-
No project / service name supplied (default)
- Filename:
.oauth-config.json
- Filename:
-
Project / service name supplied
- Project name:
hermes
- Filename:
.oauth-config-hermes.json
- Project name:
Note: When updating oauth client details be sure to delete any .oauth-token*.json file.
const oauth = require('basic-oauth2');
// Without supplied project name (default)
async function accessTokenWithoutProjectName() {
const token = await oauth.oauthToken();
// ...
}
// With supplied project name
async function accessTokenWithProjectName() {
const token = await oauth.oauthToken('hermes');
// ...
}
// HTTP call without project name (default)
async function call() {
try {
// http is an axios instance
const http = await bo.http();
const response = await http.get('https://example.com/api/test');
// ...
} catch(error) {
console.error(error.request);
}
}
// HTTP call with project name
async function call() {
try {
// http is an axios instance
const http = await bo.http('hermes');
const response = await http.get('https://example.com/api/test');
// ...
} catch(error) {
console.error(error.request);
}
}
It's highly suggested to add the following entries into your .gitignore file
.oauth-config*.json
.oauth-token*.json
One day...
MIT