api/token

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 login and secret columns use properties from the generated session by module:api/token.create.

    Parsed token session is stored in the context.session as 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:

  • type: token
  • id - user login, public part of the token, prefix + UUIDv4
  • secret: second part of the token as UUIDv4, hidden property

(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 with module: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: token
    • id - generated UUIVv4 session id, public part, this is user login
    • secret: generated UUIDv4 hashed with SHA256, to be saved in the users table as secret
    • token: concatenated id and unhashed secret, to be used in API Authorization header
Source:
Parameters:
Name Type Attributes Description
context RequestContext
options object <optional>
Properties
Name Type Attributes Description
prefix string <optional>

prefix for the login part

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) or Authorization: Bearer token,

    An API tokens are created by module:api/token.create and parsed by module:api/token.parse.

Source:
Parameters:
Name Type Description
context RequestContext
secret string