module:api/token
- Description:
API token based authentication, it reuses the users module to keep API token inside the same users table, as a special type of user, the
loginandsecretcolumns use properties from the generated session bymodule:api/token.create.Parsed token session is stored in the
context.sessionas an object:{ type: "token", id: string, secret: string }`API tokens can be created via shell command:
# bksh -user-add-token name test flags api -prefix api_ 'api_7e717a99e4b642ce88010629d32921b7caf92f4d165c46f59f983f880aa25c78'
- Source:
Methods
(static) parse(context) → {undefined|object}
- Description:
Parse API token and return as session object with id and secret if valid or undefined
- Source:
Parameters:
| Name | Type | Description |
|---|---|---|
context |
RequestContext |
Returns:
| Type | Description |
|---|---|
| undefined | object |
parsed token session if present, the3 format of the object is:
|
(static) prepare(context, optionsopt) → {object}
- Description:
Create an API token to be saved in the database, stores it in
context.session. The format is compatible withmodule:api/session.Generated login and secret are random UUIDv4, so secret hash without a salt is more about database exposure of the secret and not weak encryption.
The session object contains the following properties:
type:tokenid- generated UUIVv4 session id, public part, this is user loginsecret: generated UUIDv4 hashed with SHA256, to be saved in the users table as secrettoken: concatenated id and unhashed secret, to be used in API Authorization header
- Source:
Parameters:
| Name | Type | Attributes | Description | ||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|
context |
RequestContext | ||||||||||
options |
object |
<optional> |
Properties
|
Returns:
| Type | Description |
|---|---|
| object |
a session object |
Example
const session = api.token.create(context, { prefix:"test_" })
{ type: "token", id: 'test_a2a3912ba6df4d1ebc87278be49f8aa0' }
const user = {
login: session.id,
secret: session.secret,
name: "Test user",
....
};
await db.aput("bk_user", user);
(static) verify(context, secret)
- Description:
Verify API token from Authorization header and sets user in the context on success, this can be used standalone or as middleware.
It must be in format:
Authorization: Basic base64(token)orAuthorization: Bearer token,An API tokens are created by
module:api/token.createand parsed bymodule:api/token.parse.
- Source:
Parameters:
| Name | Type | Description |
|---|---|---|
context |
RequestContext | |
secret |
string |