API Tokens & Programmatic Authentication #
Back to docs index | Back to project README
MBKAuthe provides secure Personal API Tokens for automation scripts, CI/CD pipelines, and microservice-to-microservice communication.
1. Token Structure & Storage #
API tokens generated by MBKAuthe follow a standard prefixed format:
mbk_usr_live_8f4b92c10a3d4e7f8b9a0c1d2e3f4a5b6c7d8e9f0
- Prefix: Identifies token type and purpose (
mbk_usr_,mbk_svc_). - Storage: Raw token strings are returned only once at creation time. In the database (
mbkcore_api_tokens), tokens are stored as SHA-256 hashes (token_hash) alongside their visible prefix. - Timing-Safe Comparison: Authentication compares hashed tokens in constant time using
crypto.timingSafeEqual.
2. Token Scopes & Permissions #
Permissions are stored as JSONB in the database with strict schema validation:
{
"scope": "read-only",
"allowed_apps": ["portal", "mbkauthe"]
}
scope:"read-only": Permits only safe HTTP methods (GET,HEAD,OPTIONS)."write": Permits mutating HTTP methods (POST,PUT,PATCH,DELETE).
allowed_apps: Limits token authorization to specific ecosystem services.
3. Authenticating with API Tokens #
Pass the token in the standard Authorization HTTP header:
curl -H "Authorization: Bearer mbk_usr_live_8f4b92c10a3d..." https://portal.mbktech.org/api/user/profile
Direct Middleware Usage #
import express from "express";
import { sessRole } from "mbkauthe";
const app = express();
// sessRole accepts both valid cookie sessions and valid API bearer tokens
app.get("/api/data", sessRole("normaluser"), (req, res) => {
res.json({ data: "Protected information", user: req.session.user });
});
4. Server-to-Server Authentication: authenticate(token)
#
For fixed shared secret token authentication between microservices:
import { authenticate } from "mbkauthe";
app.post(
"/api/internal/webhook",
authenticate(process.env.MAIN_SECRET_TOKEN),
(req, res) => {
res.json({ status: "webhook accepted" });
}
);