STAFFCHAPTER 34

Open banking: the CBN framework, with UK and Brazil compared

A lender wants ninety days of one customer's transactions. Give it a token that names the customer, the fields, the purpose and an end date, refuse everything else, and log every call, refused or not

60 MINPAYMENTSUPDATED 2026-11-14
PREDICT

A lender holds a valid consent token that a customer granted for their own account. The lender calls the transactions endpoint with a different customer's account number in the path. What should the bank's API do?

Banks hold data that other businesses want: a lender wants cash flow, a budgeting app wants balances. Open banking is the arrangement in which a bank gives such a business access to a customer’s data, or lets it start a payment, through an application programming interface (API), with the customer’s consent and under a regulator’s rules. The bank is the API provider. The business is the API consumer. The customer decides. This chapter is about the data half: reading accounts. It does not cover payment initiation, which is a different risk.

What a lender does without it

A PDF or CSV statement is a document the customer can edit. The lender cannot tell whether the file is the bank’s, and re-keying it into a credit model is slow. A shared password is worse. The lender’s software logs in as the customer, so the bank cannot tell the customer from the lender’s robot, cannot limit what it reads, and cannot revoke it without changing the customer’s own password. The customer has also given the lender everything: the ability to move money, not only to read it. This practice is often called screen scraping.

Open banking replaces both with a narrower thing: a consent, a record that this customer allowed this participant to read these data for this purpose until this time. The rest of the chapter is what such a record has to contain and what the API must do with it.

Customerdecides, can revokeNorthmere (API provider)consent records: customer,scopes, purpose, expiryAPI: check, then answeraccess log: every callLenderAPI consumer1 consent2 token3 call4 the bank answers 200 with only the consented fields, or 401 or 403 with a reason5 either way, one row goes into the access logCustomer revokes at any time: the next call in step 3 is a 403

What the CBN documents say, and what this chapter could read

A caution about sources before any rule. The website of the Central Bank of Nigeria (CBN) did not open from the environment where this chapter was written. Every statement about the CBN’s documents below rests on search results: the CBN’s document titles and URLs as the search tool listed them, extracts of their text in those results, and the summaries that law firms and commentators have published. Where those summaries disagree, the chapter says so. Read the CBN’s text before you design to it. The notes below tell you what to look for, not what the text says.

The CBN issued its Regulatory Framework for Open Banking in Nigeria on 17 February 2021, by circular to deposit money banks and payment service providers. Search extracts of the circular and law-firm summaries say it divides the data and services shared through APIs into four categories, each with a risk rating, and groups participants into four tiers, each limited to some categories. This is read from search extracts and summaries; the circular’s full text was not openedas of 2026-11.

The four categories, as the summaries describe them (the descriptions in the second column are this chapter’s paraphrase of the names), matter more to your design than any other single idea in the framework, because the risk rating decides how much care the API needs.

Category What it covers, as summarised Risk rating, as summarised In this chapter’s lab
PIST (Product Information and Service Touchpoints) Product information and the points where customers reach the bank, such as fees and branch locations Low Not built: it is public data
MIT (Market Insight Transactions) Market-level information rather than one customer’s Moderate Not built
PIFT (Personal Information and Financial Transaction) An individual customer’s personal information and account activity High The lab’s three scopes
PAST (Profile, Analytics and Scoring Transaction) Analytical outputs about a customer: profiles, scores High and sensitive Not built: a lender computes its own

Search extracts of the circular’s access table, which a law firm (Banwo & Ighodalo) reproduces, give four tiers: Tier 0, participants without a regulatory licence, which must be sponsored by a Tier 2 or Tier 3 participant and may reach PIST and MIT; Tier 1, participants admitted through the CBN regulatory sandbox, which may also reach PIFT; Tier 2, licensed payment service providers and other financial institutions; and Tier 3, deposit money banks, both of which may reach all four categories. One law-firm summary differs on PAST, giving it to Tiers 1 and 2. The risk ratings come from the same search results. Read the circular’s own table before you design to itas of 2026-11..

Your lender is asking for PIFT: a customer’s transactions. That is the high-risk row, and the one where a consent token is the whole point.

The second document turns the framework into duties.

The CBN’s Operational Guidelines for Open Banking in Nigeria PDF shows approval in March 2023 and says it implements the 2021 framework; law-firm and press coverage gives 7 March 2023 as the release date, after an exposure draft in May 2022. Commentators report that participants are classed by the roles they perform, that customers must be able to grant, view, decline and revoke consent, that consent is re-validated annually (or sooner if the accessing party has not used the service for 180 days), and that participants register on an Open Banking Registry that the CBN maintains. A KPMG slide deck lists audit trails among the requirements. These are commentary; the guidelines’ text was not openedas of 2026-11.

.

Three details deserve a flag, because the summaries are thin or differ.

First, the registry, the list of participants and approved APIs. The summaries seen say the CBN establishes and maintains it. Whether it also covers every participant, and who runs it day to day, was not confirmed. The lab’s participants table stands in for a registry and says nothing about the real one.

Second, audit trails. A KPMG slide deck lists audit trails as required. The chapter could not find, in the search results, what the logs must contain or how long they must be kept. The access log in the lab is good engineering whatever the text says. Find any retention duty in the document before you promise one.

Third, the API standard. A CBN official was reported in October 2025 as saying that the CBN had put together a governance structure and was building a standardised API template. The chapter found no published specification dated later. If you build now, build so that the field names and paths can change in one place.

Where Nigeria stands: live, or not?

This is the question your lender will ask first, and the honest answer is that it is uncertain.

Press reports found by search in November 2026 say that a national launch announced for August 2025 did not happen as planned. TechCabal reported on 16 October 2025 that a CBN official said open banking “hasn’t gone live yet”, and Vanguard’s report of the same panel says no new launch date was given. Press and law-firm pieces from early 2026 mention a CBN roadmap and a phased rollout through 2026, and they disagree: one February 2026 analysis describes the framework as live from 1 August 2025, while a later piece calls that date a regulatory milestone, not an operational one. No CBN circular confirming a go-live date was found, so the status in November 2026 is unconfirmed. These are secondary sources; none is the CBNas of 2026-11..

So the position for a bank in November 2026 is this. The framework and the guidelines exist. Whether the full regime is in force, and from what date, you cannot confirm from the sources here. Ademola should not promise a lender a date. He can promise that the API will be built to the guidelines’ consent model, and that it can be shown to an examiner.

Take the guidelines’ consent duties as summarised and turn each into a field or a check. A consent in the lab is one row with these parts.

Part Why it exists What goes wrong without it
Customer The consent is for one customer’s data A token for one customer reads another’s account
Participant Who the bank gave it to You cannot say who looked, or stop one lender without stopping all
Scopes A scope is a named permission, such as transactions:read. The scope is also the field list A lender that asked for balances gets transactions
Purpose What the data is for, in words the customer saw Data collected for a loan check is reused for marketing
Expiry Consent is time-bound A token granted once reads forever
Revoked at The customer changed their mind The only way to stop access is to change the password, or to ask the lender
Token hash The bank stores a SHA-256 of the token, never the token A copy of the database is a bag of working keys

The token is a bearer token: whoever holds it can use it, with no further proof. That is why it is long and random (24 bytes from Python’s secrets module in the lab, so a 36-character string with a four-character prefix) and why only its hash is stored. A password needs a slow hash because people choose weak ones. A random 24-byte token has no weak guesses, so a fast SHA-256 is enough. A real deployment uses HTTPS only and short token lifetimes. The lab runs on plain HTTP on 127.0.0.1 so that you can read every byte, and that is the one thing you must not copy.

The lab has three scopes, all in the PIFT row: transactions:read opens the date, direction, amount, kind and reference of each entry; counterparty:read adds the code of the other bank; balance:read opens the balance. A participant can be granted only the scopes its registration allows. The lab’s second lender may hold balance:read and nothing else, and the bank refuses at the door, when the consent is made, if it asks for more.

The order of the checks

When a call arrives, the API asks its questions in an order, and the order decides what the lender learns and what the log says.

Order Question Answer if it fails
1 Does the token match a consent? 401, invalid_token
2 Has the customer revoked it? 403, consent_revoked
3 Has it expired? 403, consent_expired
4 Is the account the one the consent names? 403, wrong_account
5 Does a granted scope cover this endpoint? 403, scope_missing
6 Only now: read the data and return the permitted fields 200

The split between 401 and 403 is a convention. 401 means “I cannot tell who you are” and 403 means “I know who you are and the answer is no”. Many APIs answer an expired or revoked token with 401; the lab uses 403 with a reason code so that a lender can tell “ask the customer again” from “your token is wrong”.

Two design choices keep this safe. The API fails closed: a bug that raises an error returns 500 and no data, and the error is logged. And the fields come from the scope, not from the caller: the lender cannot ask for counterparty_bank by adding a query parameter. The lender sends no field list at all. What it receives is decided by the consent.

The log an examiner reads

Each call, allowed or refused, writes one row: when, which consent, which participant, whose data the call asked for, the path, the status, how many rows came back and the reason. The token never goes in the log, and neither does a transaction amount. The log answers three questions that come up once a regulator or a customer asks.

  • Who looked at my data? Filter by the customer. The lab’s audit endpoint does this.
  • Did anything read data it should not have? Join the log to the consents and compare the customer on the call with the customer on the consent. The lab does this in SQL in step 8. A well-built API returns an empty list. The break at the end shows what the list looks like when the check is missing.
  • What did a lender actually receive? Rows returned, by participant. It is a number you can set against what the customer was told.

The log itself names customers, so treat it as personal data; the Nigeria Data Protection Act 2023 applies, and this chapter does not teach it.

How it goes wrong

Each failure below has a test in the lab.

  • A valid token reads another customer’s account. The check in position 4 above. It passes every test that uses one customer.
  • Scope creep. The lender asks for everything “in case”, and the bank grants it. A scope list that is easy to widen is a scope list that is always wide. The lab refuses a scope the participant is not registered for.
  • Consent that never ends. A token with no expiry is a standing permission nobody remembers. The lab caps one consent at 90 days (an invented limit) and refuses a longer request.
  • Revocation that does not bite. If a lender or the bank caches the consent, the customer’s “revoke” takes effect later. The lab reads the consent row on every call, so the next call after a revoke is a 403. A cache needs an invalidation story.
  • Secrets in logs. A token in an access log or an error message is a leak by another route. The lab logs the consent id, never the token.
  • The customer does not understand. A consent screen nobody reads is not consent in any useful sense. How you show scope and purpose is a design problem the lab does not touch.
  • The lender computes something the customer did not expect. A score built from transactions is the kind of output the PAST category appears to describe. Check the text before the bank sells one.

The UK, the EU and Brazil

Three other regimes shaped the Nigerian one or are used as comparison. They differ most in who started them and who was made to take part.

UK EU Brazil
What started it A competition-authority order: the Competition and Markets Authority (CMA) Retail Banking Market Investigation Order 2017 A directive: the Payment Services Directive (PSD2), Directive (EU) 2015/2366 A joint resolution of the National Monetary Council and the central bank: Joint Resolution No 1 of 2020
Who must take part The nine largest banks and building societies in Great Britain and Northern Ireland, under the order Providers of payment accounts that are accessible online The institutions the resolution covers, in phases
Consent, as summarised below The third-party provider reconfirms it at least every 90 days Explicit, and limited to the service the user asked for Set in the resolution and its later amendments
Timeline, as summarised below All nine have completed the roadmap, as its implementation entity reports Directive text adopted in 2015 Planned in phases from 30 November 2020 to October 2021, as summaries say

The Open Banking Limited page on the CMA Retail Banking Market Investigation Order 2017 says the order required the nine largest banks and building societies in Great Britain and Northern Ireland to adopt open banking, with common standards as the remedy. Search results show the CMA determined in January 2023 that six of the nine had completed the roadmap, and the implementation entity’s own announcement says all nine have since completed it; one trade-press piece dates that to September 2024. The order’s full text was not readas of 2026-11..

PSD2 Article 67 lets an account information service provider deliver its service only on the user’s explicit consent (paragraph 2(a)), limits it to using, accessing or storing data for the service the user explicitly requested (paragraph 2(f)), and does not make the service depend on a contract between that provider and the account-holding bank (paragraph 4). The source is the original adopted text as published on legislation.gov.uk, not the current consolidated version; read EUR-Lex for amendmentsas of 2026-11.

The FCA’s policy statement PS21/19 (29 November 2021) is summarised in search results as replacing the 90-day re-authentication of the customer at the bank with a duty on the third-party provider to reconfirm the customer’s consent every 90 days, and to stop accessing the data until consent is reconfirmed if the customer does not. The FCA strongly encouraged banks to apply the new exemption within four months. Read from search summaries of the policy statement; its text was not openedas of 2026-11..

Brazil’s Joint Resolution No 1 was published on 4 May 2020 by the National Monetary Council (CMN) and the Central Bank of Brazil, and the central bank hosts an English translation. It provides for open banking among financial institutions, payment institutions and other institutions the central bank licenses. Law-firm and press summaries say the rollout was planned in phases from 30 November 2020 to October 2021 (the International Bar Association describes four phases), and a later central bank presentation, as summarised, shows the first phase live from 1 February 2021, so the schedule slipped. The resolution has been amended since, for example by Joint Resolution 10 of 2024. The article-level consent wording and the amendments were not readas of 2026-11..

Beside Nigeria, one difference stands out. In the UK and Brazil an authority set dates and named the institutions that had to comply. In Nigeria, as far as the sources show, the framework and guidelines exist and the date is not confirmed, so a bank cannot build to a deadline and cannot be sure it will not need to.

What the four share is the pattern in this chapter: an explicit, scoped, time-limited consent, the bank deciding what the API returns, and a record of every access.

What it means for the bank’s business

The framework is regulation, and the decision it forces is a business one.

Role. Northmere is an API provider for its own customers’ data. It could also be an API consumer, reading other banks’ data for its own lending, if the regime allows. Read which duties the guidelines give to which role.

Cost. A provider builds and runs a consent service, an access log, security controls, a screen where customers view and revoke, and support for lenders and for disputes. The sources found no revenue line for this, and say nothing here about what a bank may charge a consumer for access.

Risk. PIFT is a high-risk category. A bug that returns the wrong customer’s data is a loss of trust that outlives the fix, and the lab’s break is one line long.

Position. Customers who can share data easily can also leave easily, and a lender that sees a customer’s whole flow can compete with the bank’s own lending. Which effect dominates is a judgment for Ademola, not a result of this chapter.

Timing. Because the go-live date is unconfirmed, the question is how much to build ahead of it. The Lending course’s credit data in Nigeria chapter covers what lenders do with bureau data today.

LAB Serve scoped account data behind consent tokens, revoke the consent, and read the log ~60 MIN
YOU NEEDPython 3.9 or later (standard library only)labs/finance with the data generated (python3 generate.py)Two terminals: one for the server, one for the lenderNo Docker, no packages

You work in labs/finance. You write seven small files there: ob_setup.py, ob_server.py, ob_client.py, ob_consent.py, ob_lender.py, ob_probe.py and ob_examine.py. The break is a one-line edit to a copy of the server. You never touch data/finance.sqlite: step 1 copies it to data/openbanking.sqlite. Owoleaf is a wallet company, not a bank. Its books stand in for Northmere’s because they give you accounts, entries and a checker. Account 9000000002 is wallet 2 (a merchant), and the lender is asking about its last three months. The scopes, the participants, the 90-day cap and the bank key are invented for this lab. All queries go through Python’s sqlite3 module; no sqlite3 program is needed. The server answers on port 9000, and everything the lender does goes through ob_client.py.

1. Copy the books and add three tables. Save ob_setup.py. It adds participants (the lab’s stand-in for a registry), consents and access_log. Then check that the copy still balances.

"""Step 1: copy the books and add the three tables a consent API needs.
Illustrative: the participants, scopes and limits below are invented for this lab."""
import shutil
import sqlite3

SRC, DB = "data/finance.sqlite", "data/openbanking.sqlite"
shutil.copy(SRC, DB)
db = sqlite3.connect(DB)
db.executescript("""
-- Stand-in for a registry of API consumers: who may ask for what.
CREATE TABLE participants (
  id             TEXT PRIMARY KEY,
  name           TEXT NOT NULL,
  allowed_scopes TEXT NOT NULL            -- comma-separated
);
-- One row per consent. The token itself is never stored, only its SHA-256.
CREATE TABLE consents (
  id             INTEGER PRIMARY KEY,
  token_hash     TEXT NOT NULL UNIQUE,
  customer_id    INTEGER NOT NULL REFERENCES customers(id),
  participant_id TEXT NOT NULL REFERENCES participants(id),
  scopes         TEXT NOT NULL,
  purpose        TEXT NOT NULL,
  created_at     INTEGER NOT NULL,        -- Unix seconds
  expires_at     INTEGER NOT NULL,
  revoked_at     INTEGER
);
-- One row per call, allowed or refused. The access log an examiner reads.
CREATE TABLE access_log (
  id             INTEGER PRIMARY KEY,
  at             INTEGER NOT NULL,
  consent_id     INTEGER,                 -- NULL when the token matched no consent
  participant_id TEXT,
  customer_id    INTEGER,                 -- whose data the call asked for
  method         TEXT NOT NULL,
  path           TEXT NOT NULL,
  status         INTEGER NOT NULL,
  rows_returned  INTEGER NOT NULL,
  reason         TEXT NOT NULL
);
INSERT INTO participants VALUES
  ('LND-1', 'A lender (illustrative)',   'transactions:read,counterparty:read,balance:read'),
  ('LND-2', 'Another lender (illustrative)', 'balance:read');
""")
db.commit()
for t in ("customers", "transactions", "entries", "participants", "consents", "access_log"):
    print(f"{t:13s}", db.execute(f"SELECT COUNT(*) FROM {t}").fetchone()[0])
python3 ob_setup.py
python3 check.py --db data/openbanking.sqlite | tail -1
customers     2000
transactions  83887
entries       191103
participants  2
consents      0
access_log    0
OK: all invariants hold

The books are unchanged and the new tables are empty. check.py knows nothing about them, which is right: they hold consents and calls, not money.

2. Save the server and start it. ob_server.py is the whole API: two routes for lenders, three for the bank, a grant function that refuses what a participant may not hold, and one account function that asks the six questions of the table above in order. Read account before you run it.

"""A consent-token API over the lab's books, on http.server and sqlite3 only.

Bank side (needs the X-Bank-Key header; stands in for the customer's signed-in banking app):
  POST /consents                  {customer_id, participant_id, scopes, purpose, ttl_seconds}
  POST /consents/{id}/revoke
  GET  /audit?customer_id=N
Lender side (needs Authorization: Bearer <token>):
  GET  /accounts/{account_number}/transactions?from=&to=&limit=&offset=
  GET  /accounts/{account_number}/balance

Scopes, limits and the key are ILLUSTRATIVE, invented for this lab. Money is integer kobo.
"""
import argparse
import hashlib
import json
import re
import secrets
import sqlite3
import time
from http.server import BaseHTTPRequestHandler, HTTPServer
from urllib.parse import parse_qs, urlparse

BANK_KEY = "bank_lab_key"                 # the lab's stand-in for a signed-in customer session
SCOPES = {"transactions:read", "counterparty:read", "balance:read"}
MAX_TTL = 90 * 24 * 3600                  # illustrative cap on one consent: 90 days
MAX_PAGE = 100
ACCT = re.compile(r"^9\d{9}$")            # wallet account number: 9 and the customer id in nine digits

DB = None


def now():
    return int(time.time())


def sha(token):
    return hashlib.sha256(token.encode()).hexdigest()


def log(consent, customer_id, method, path, status, rows, reason):
    DB.execute(
        "INSERT INTO access_log (at, consent_id, participant_id, customer_id, method, path, status, rows_returned, reason)"
        " VALUES (?,?,?,?,?,?,?,?,?)",
        (now(), consent["id"] if consent else None, consent["participant_id"] if consent else None,
         customer_id, method, path, status, rows, reason))
    DB.commit()


class Handler(BaseHTTPRequestHandler):
    def log_message(self, *a):            # the access_log table is the log; keep the console quiet
        pass

    def send(self, status, body):
        data = json.dumps(body).encode()
        self.send_response(status)
        self.send_header("Content-Type", "application/json")
        self.send_header("Content-Length", str(len(data)))
        self.end_headers()
        self.wfile.write(data)

    def read_json(self):
        n = int(self.headers.get("Content-Length") or 0)
        return json.loads(self.rfile.read(n) or b"{}")

    def do_GET(self):
        self.route("GET")

    def do_POST(self):
        self.route("POST")

    def route(self, method):
        u = urlparse(self.path)
        parts = [p for p in u.path.split("/") if p]
        q = {k: v[0] for k, v in parse_qs(u.query).items()}
        try:
            if parts[:1] == ["accounts"] and len(parts) == 3 and method == "GET":
                return self.account(parts[1], parts[2], q, u.path)
            if parts[:1] in (["consents"], ["audit"]):
                if self.headers.get("X-Bank-Key") != BANK_KEY:
                    return self.send(401, {"error": "bank_key_required"})
                if parts == ["consents"] and method == "POST":
                    return self.grant(self.read_json())
                if len(parts) == 3 and parts[2] == "revoke" and method == "POST":
                    return self.revoke(int(parts[1]))
                if parts == ["audit"] and method == "GET":
                    return self.audit(int(q["customer_id"]))
            return self.send(404, {"error": "not_found"})
        except (ValueError, KeyError, json.JSONDecodeError) as e:
            return self.send(400, {"error": "bad_request", "detail": str(e)})
        except Exception as e:             # fail closed: say nothing about the data
            log(None, None, method, u.path, 500, 0, "server_error")
            return self.send(500, {"error": "server_error"})

    # ---- bank side -------------------------------------------------------------
    def grant(self, b):
        cust = DB.execute("SELECT id FROM customers WHERE id=?", (b["customer_id"],)).fetchone()
        part = DB.execute("SELECT * FROM participants WHERE id=?", (b["participant_id"],)).fetchone()
        scopes = set(b["scopes"])
        if not cust or not part:
            return self.send(400, {"error": "unknown_customer_or_participant"})
        if not scopes or not scopes <= SCOPES:
            return self.send(400, {"error": "unknown_scope"})
        if not scopes <= set(part["allowed_scopes"].split(",")):
            return self.send(403, {"error": "scope_not_allowed_for_participant",
                                   "allowed": part["allowed_scopes"].split(",")})
        if not str(b.get("purpose", "")).strip():
            return self.send(400, {"error": "purpose_required"})
        ttl = int(b["ttl_seconds"])
        if not 1 <= ttl <= MAX_TTL:
            return self.send(400, {"error": "ttl_out_of_range", "max_seconds": MAX_TTL})
        token = "obt_" + secrets.token_urlsafe(24)
        t = now()
        cur = DB.execute(
            "INSERT INTO consents (token_hash, customer_id, participant_id, scopes, purpose, created_at, expires_at)"
            " VALUES (?,?,?,?,?,?,?)",
            (sha(token), b["customer_id"], b["participant_id"], ",".join(sorted(scopes)), b["purpose"], t, t + ttl))
        DB.commit()
        return self.send(201, {"consent_id": cur.lastrowid, "access_token": token,
                               "scopes": sorted(scopes), "expires_at": t + ttl})

    def revoke(self, cid):
        cur = DB.execute("UPDATE consents SET revoked_at=? WHERE id=? AND revoked_at IS NULL", (now(), cid))
        DB.commit()
        return self.send(200, {"consent_id": cid, "revoked": cur.rowcount == 1})

    def audit(self, customer_id):
        rows = DB.execute("SELECT * FROM access_log WHERE customer_id=? ORDER BY id", (customer_id,)).fetchall()
        return self.send(200, {"customer_id": customer_id, "calls": [dict(r) for r in rows]})

    # ---- lender side -----------------------------------------------------------
    def account(self, acct, what, q, path):
        auth = self.headers.get("Authorization", "")
        token = auth[7:] if auth.startswith("Bearer ") else ""
        consent = DB.execute("SELECT * FROM consents WHERE token_hash=?", (sha(token),)).fetchone() if token else None
        customer_id = int(acct[1:]) if ACCT.match(acct) else None

        def refuse(status, reason, extra=None):
            log(consent, customer_id, "GET", path, status, 0, reason)
            return self.send(status, {"error": reason, **(extra or {})})

        if consent is None:
            return refuse(401, "invalid_token")
        if consent["revoked_at"] is not None:
            return refuse(403, "consent_revoked")
        if consent["expires_at"] <= now():
            return refuse(403, "consent_expired")
        if customer_id is None or consent["customer_id"] != customer_id:
            return refuse(403, "wrong_account")          # a valid token for someone else's account
        need = {"transactions": "transactions:read", "balance": "balance:read"}.get(what)
        if need is None:
            return refuse(404, "not_found")
        granted = set(consent["scopes"].split(","))
        if need not in granted:
            return refuse(403, "scope_missing", {"needed": need})
        wallet = DB.execute("SELECT id FROM accounts WHERE code=?", (f"wallet:{customer_id}",)).fetchone()
        if wallet is None:
            return refuse(404, "no_such_account")

        if what == "balance":
            r = DB.execute("SELECT COALESCE(SUM(CASE direction WHEN 'credit' THEN amount_kobo ELSE -amount_kobo END),0)"
                           " FROM entries WHERE account_id=?", (wallet["id"],)).fetchone()
            log(consent, customer_id, "GET", path, 200, 1, "ok")
            return self.send(200, {"account": acct, "currency": "NGN", "balance_kobo": r[0]})

        lo, hi = q.get("from", "0000-01-01"), q.get("to", "9999-12-31")
        try:
            limit = max(1, min(int(q.get("limit", 50)), MAX_PAGE))   # SQLite reads LIMIT -1 as "no limit"
            offset = max(0, int(q.get("offset", 0)))
        except ValueError:
            return refuse(400, "bad_paging")                        # logged like every other call
        extra = "counterparty:read" in granted
        rows = DB.execute(
            "SELECT e.id, e.posted_at, e.direction, e.amount_kobo, t.kind, t.external_ref, t.counterparty_bank"
            " FROM entries e JOIN transactions t ON t.id = e.transaction_id"
            " WHERE e.account_id=? AND e.posted_at >= ? AND e.posted_at < ? ORDER BY e.posted_at, e.id LIMIT ? OFFSET ?",
            (wallet["id"], lo, hi, limit, offset)).fetchall()
        out = []
        for r in rows:
            item = {"id": r["id"], "booked_at": r["posted_at"], "direction": "in" if r["direction"] == "credit" else "out",
                    "amount_kobo": r["amount_kobo"], "kind": r["kind"], "reference": r["external_ref"]}
            if extra:
                item["counterparty_bank"] = r["counterparty_bank"]
            out.append(item)
        log(consent, customer_id, "GET", path, 200, len(out), "ok")
        return self.send(200, {"account": acct, "currency": "NGN", "count": len(out), "next_offset": offset + len(out)
                               if len(out) == limit else None, "transactions": out})


def main():
    global DB
    ap = argparse.ArgumentParser()
    ap.add_argument("--port", type=int, default=9000)
    ap.add_argument("--db", default="data/openbanking.sqlite")
    a = ap.parse_args()
    DB = sqlite3.connect(a.db)
    DB.row_factory = sqlite3.Row
    print(f"openbanking on http://127.0.0.1:{a.port}  db {a.db}", flush=True)
    HTTPServer(("127.0.0.1", a.port), Handler).serve_forever()


main()

In its own terminal:

python3 ob_server.py
openbanking on http://127.0.0.1:9000  db data/openbanking.sqlite

Leave it running. The server prints nothing else: the log is the access_log table. The bank routes need an X-Bank-Key header, a stand-in for the customer’s signed-in session in the bank’s app. A real consent is made on the bank’s side, where the customer proves who they are, and the lender never sees that step.

3. The customer grants a consent. Save ob_client.py (one HTTP call that returns the status and the JSON) and ob_consent.py (grant, revoke and audit). Grant the first lender two scopes for an hour.

"""Shared by the lab scripts: one HTTP call, returning (status, parsed JSON)."""
import json
import urllib.error
import urllib.request

BASE = "http://127.0.0.1:9000"
BANK_KEY = "bank_lab_key"


def call(method, path, token=None, bank=False, body=None, base=BASE):
    headers = {"Content-Type": "application/json"}
    if token:
        headers["Authorization"] = f"Bearer {token}"
    if bank:
        headers["X-Bank-Key"] = BANK_KEY
    data = json.dumps(body).encode() if body is not None else None
    req = urllib.request.Request(base + path, data=data, method=method, headers=headers)
    try:
        with urllib.request.urlopen(req) as r:
            return r.status, json.loads(r.read())
    except urllib.error.HTTPError as e:
        return e.code, json.loads(e.read())
"""The customer's side, as the bank's app would drive it: grant, revoke, and see who looked.
  python3 ob_consent.py grant --customer 2 --participant LND-1 --scopes transactions:read,balance:read --ttl 3600
  python3 ob_consent.py revoke --id 1
  python3 ob_consent.py audit --customer 2
"""
import argparse
import datetime
import sys

import ob_client

ap = argparse.ArgumentParser()
sub = ap.add_subparsers(dest="cmd", required=True)
g = sub.add_parser("grant")
g.add_argument("--customer", type=int, required=True)
g.add_argument("--participant", required=True)
g.add_argument("--scopes", required=True)
g.add_argument("--ttl", type=int, default=3600)
g.add_argument("--purpose", default="Affordability check for a working-capital loan application")
g.add_argument("--token-file")
r = sub.add_parser("revoke")
r.add_argument("--id", type=int, required=True)
u = sub.add_parser("audit")
u.add_argument("--customer", type=int, required=True)
a = ap.parse_args()

if a.cmd == "grant":
    status, body = ob_client.call("POST", "/consents", bank=True, body={
        "customer_id": a.customer, "participant_id": a.participant, "scopes": a.scopes.split(","),
        "purpose": a.purpose, "ttl_seconds": a.ttl})
    if status != 201:
        print(status, body)
        sys.exit(1)
    if a.token_file:
        open(a.token_file, "w").write(body["access_token"])
    print(f"consent {body['consent_id']} granted: scopes {','.join(body['scopes'])}, "
          f"expires in {a.ttl} s, token {body['access_token'][:8]}... ({len(body['access_token'])} characters)")
elif a.cmd == "revoke":
    status, body = ob_client.call("POST", f"/consents/{a.id}/revoke", bank=True)
    print(status, body)
else:
    status, body = ob_client.call("GET", f"/audit?customer_id={a.customer}", bank=True)
    print(f"{'at (UTC)':9} {'consent':>7} {'who':6} {'status':>6} {'rows':>4}  reason   path")
    for c in body["calls"]:
        t = datetime.datetime.fromtimestamp(c["at"], datetime.timezone.utc).strftime("%H:%M:%S")
        print(f"{t:9} {str(c['consent_id']):>7} {str(c['participant_id']):6} {c['status']:>6} {c['rows_returned']:>4}  "
              f"{c['reason']:16} {c['path']}")
python3 ob_consent.py grant --customer 2 --participant LND-1 --scopes transactions:read,balance:read --ttl 3600 --token-file data/lender1.token
consent 1 granted: scopes balance:read,transactions:read, expires in 3600 s, token obt_BwBK... (36 characters)

The token is random, so yours begins with other characters. It is returned once. The bank stores only its SHA-256, which step 8 checks. The lender receives it, and --token-file stands for that hand-over.

4. Call it as a lender would. Save ob_lender.py. It pages through three months of transactions, 100 at a time, sums them in integer kobo and reads the balance.

"""The lender: pull 90 days of a customer's transactions with a consent token and compute an affordability view.
  python3 ob_lender.py --token-file data/lender1.token --account 9000000002
All sums are integer kobo; naira appear only when printed."""
import argparse
import collections

import ob_client

ap = argparse.ArgumentParser()
ap.add_argument("--token-file", required=True)
ap.add_argument("--account", required=True)
ap.add_argument("--from", dest="lo", default="2026-04-01")
ap.add_argument("--to", dest="hi", default="2026-06-30")
a = ap.parse_args()
token = open(a.token_file).read().strip()


def naira(kobo):
    return f"₦{kobo // 100:,}.{kobo % 100:02d}"


txns, offset = [], 0
while offset is not None:
    status, body = ob_client.call("GET", f"/accounts/{a.account}/transactions?from={a.lo}&to={a.hi}&limit=100&offset={offset}",
                                  token=token)
    if status != 200:
        print(f"transactions: HTTP {status} {body}")
        raise SystemExit(1)
    txns += body["transactions"]
    offset = body["next_offset"]

inflow = sum(t["amount_kobo"] for t in txns if t["direction"] == "in")
outflow = sum(t["amount_kobo"] for t in txns if t["direction"] == "out")
by_kind = collections.Counter(t["kind"] for t in txns)
print(f"{a.account}: {len(txns)} transactions from {a.lo} to {a.hi}")
print(f"  in  {inflow:>14,} kobo  {naira(inflow)}")
print(f"  out {outflow:>14,} kobo  {naira(outflow)}")
print(f"  net {inflow - outflow:>14,} kobo  {naira(inflow - outflow)}")
print("  kinds:", dict(sorted(by_kind.items())))
print("  fields seen:", sorted(txns[0]))
status, body = ob_client.call("GET", f"/accounts/{a.account}/balance", token=token)
print(f"balance: HTTP {status}", body)
python3 ob_lender.py --token-file data/lender1.token --account 9000000002
9000000002: 185 transactions from 2026-04-01 to 2026-06-30
  in     474,361,900 kobo  ₦4,743,619.00
  out    468,871,528 kobo  ₦4,688,715.28
  net      5,490,372 kobo  ₦54,903.72
  kinds: {'funding_transfer': 131, 'p2p_transfer': 8, 'payout_nip': 46}
  fields seen: ['amount_kobo', 'booked_at', 'direction', 'id', 'kind', 'reference']
balance: HTTP 200 {'account': '9000000002', 'currency': 'NGN', 'balance_kobo': 11714513}

Check the sums yourself: 185 entries on the wallet account between the two dates, ₦4,743,619.00 credited and ₦4,688,715.28 debited, which differ by 5,490,372 kobo. The lender needed two requests for the transactions (100 and 85 rows). It saw six fields per entry and no counterparty bank, because it did not hold counterparty:read. Almost everything that came in went out: that is what a wallet does, and a lender reading it as cash flow is reading the money’s route, not the merchant’s earnings.

5. Ask for what the consent does not cover. Save ob_probe.py. It makes seven calls: five that should be refused, and two that succeed to show what a narrow and a wider scope return.

"""Step 5: ask for what the consent does not cover, and watch each refusal."""
import sys

import ob_client

token = open(sys.argv[1]).read().strip()


def show(label, status, body):
    if "error" in body:
        detail = body["error"] + (f" ({body['needed']})" if "needed" in body else "")
    elif "transactions" in body:
        detail = f"{body['count']} rows, fields {sorted(body['transactions'][0])}"
    else:
        detail = str(body)
    print(f"{status}  {label:44s} {detail}")


# 1. Calls with the lender's token and with no good token.
show("no token", *ob_client.call("GET", "/accounts/9000000002/transactions"))
show("a made-up token", *ob_client.call("GET", "/accounts/9000000002/transactions", token="obt_not-a-real-token"))
show("the token, another customer's account", *ob_client.call("GET", "/accounts/9000000003/transactions", token=token))

# 2. The second lender may only hold balance:read. Asking the bank for more is refused at the door.
ask = {"customer_id": 2, "participant_id": "LND-2", "purpose": "Check a balance before a card limit",
       "ttl_seconds": 3600}
status, body = ob_client.call("POST", "/consents", bank=True, body={**ask, "scopes": ["transactions:read"]})
print(f"{status}  LND-2 asks for transactions:read                {body['error']}, allowed {body['allowed']}")
status, body = ob_client.call("POST", "/consents", bank=True, body={**ask, "scopes": ["balance:read"]})
tok2 = body["access_token"]
show("LND-2 token, transactions", *ob_client.call("GET", "/accounts/9000000002/transactions", token=tok2))
show("LND-2 token, balance", *ob_client.call("GET", "/accounts/9000000002/balance", token=tok2))

# 3. A wider consent shows one more field, because the scope says so.
status, body = ob_client.call("POST", "/consents", bank=True, body={
    **ask, "participant_id": "LND-1", "scopes": ["transactions:read", "counterparty:read"],
    "purpose": "Check which banks a borrower pays"})
show("LND-1 token with counterparty:read",
     *ob_client.call("GET", "/accounts/9000000002/transactions?limit=2", token=body["access_token"]))
python3 ob_probe.py data/lender1.token
401  no token                                     invalid_token
401  a made-up token                              invalid_token
403  the token, another customer's account        wrong_account
403  LND-2 asks for transactions:read                scope_not_allowed_for_participant, allowed ['balance:read']
403  LND-2 token, transactions                    scope_missing (transactions:read)
200  LND-2 token, balance                         {'account': '9000000002', 'currency': 'NGN', 'balance_kobo': 11714513}
200  LND-1 token with counterparty:read           2 rows, fields ['amount_kobo', 'booked_at', 'counterparty_bank', 'direction', 'id', 'kind', 'reference']

Each line is one of the failures above, closed. The third is the one the Predict asked about. The fourth never creates a token. The last shows that a wider scope changes the fields and nothing else.

6. The customer revokes. Revoke consent 1, then run the lender again.

python3 ob_consent.py revoke --id 1
python3 ob_lender.py --token-file data/lender1.token --account 9000000002
200 {'consent_id': 1, 'revoked': True}
transactions: HTTP 403 {'error': 'consent_revoked'}

The token has not changed and the lender did nothing wrong. The bank reads the consent row on every call, so revocation takes effect on the next one. The lender’s script exits with status 1.

7. The consent runs out. Grant a two-second consent, call at once, wait, and call again.

python3 ob_consent.py grant --customer 2 --participant LND-1 --scopes transactions:read,balance:read --ttl 2 --token-file data/short.token && python3 ob_lender.py --token-file data/short.token --account 9000000002; sleep 3; python3 ob_lender.py --token-file data/short.token --account 9000000002
consent 4 granted: scopes balance:read,transactions:read, expires in 2 s, token obt_KLM3... (36 characters)
9000000002: 185 transactions from 2026-04-01 to 2026-06-30
  in     474,361,900 kobo  ₦4,743,619.00
  out    468,871,528 kobo  ₦4,688,715.28
  net      5,490,372 kobo  ₦54,903.72
  kinds: {'funding_transfer': 131, 'p2p_transfer': 8, 'payout_nip': 46}
  fields seen: ['amount_kobo', 'booked_at', 'direction', 'id', 'kind', 'reference']
balance: HTTP 200 {'account': '9000000002', 'currency': 'NGN', 'balance_kobo': 11714513}
transactions: HTTP 403 {'error': 'consent_expired'}

The consent id is 4 because the probe in step 5 created two more. If the first call fails with consent_expired, your machine was slow: raise --ttl to 5 and sleep to 6.

8. Read the log as an examiner would. Save ob_examine.py, then print the customer’s view of the log with the audit command.

"""Step 8: the examiner's questions, asked of the log and the consent table in SQL."""
import sqlite3

db = sqlite3.connect("data/openbanking.sqlite")
print("calls by outcome:")
for reason, status, n in db.execute("SELECT reason, status, COUNT(*) FROM access_log GROUP BY 1, 2 ORDER BY 3 DESC, 1"):
    print(f"  {status}  {reason:16s} {n}")
print("rows of customer data handed over, by participant:")
for who, n, rows in db.execute("SELECT participant_id, COUNT(*), SUM(rows_returned) FROM access_log "
                               "WHERE status = 200 GROUP BY 1"):
    print(f"  {who}: {n} calls, {rows} rows")
n = db.execute("SELECT COUNT(*) FROM consents WHERE token_hash LIKE 'obt_%'").fetchone()[0]
print("consents holding a raw token:", n)
print("calls that read another customer's data and were allowed:")
rows = db.execute("SELECT l.id, l.consent_id, c.customer_id, l.customer_id FROM access_log l "
                  "JOIN consents c ON c.id = l.consent_id WHERE c.customer_id <> l.customer_id AND l.status = 200").fetchall()
print("  ", rows or "none")
python3 ob_consent.py audit --customer 2
python3 ob_consent.py audit --customer 3
python3 ob_examine.py
at (UTC)  consent who    status rows  reason   path
21:22:07        1 LND-1     200  100  ok               /accounts/9000000002/transactions
21:22:07        1 LND-1     200   85  ok               /accounts/9000000002/transactions
21:22:07        1 LND-1     200    1  ok               /accounts/9000000002/balance
21:22:07     None None      401    0  invalid_token    /accounts/9000000002/transactions
21:22:07     None None      401    0  invalid_token    /accounts/9000000002/transactions
21:22:07        2 LND-2     403    0  scope_missing    /accounts/9000000002/transactions
21:22:07        2 LND-2     200    1  ok               /accounts/9000000002/balance
21:22:07        3 LND-1     200    2  ok               /accounts/9000000002/transactions
21:22:07        1 LND-1     403    0  consent_revoked  /accounts/9000000002/transactions
21:22:08        4 LND-1     200  100  ok               /accounts/9000000002/transactions
21:22:08        4 LND-1     200   85  ok               /accounts/9000000002/transactions
21:22:08        4 LND-1     200    1  ok               /accounts/9000000002/balance
21:22:11        4 LND-1     403    0  consent_expired  /accounts/9000000002/transactions
at (UTC)  consent who    status rows  reason   path
21:22:07        1 LND-1     403    0  wrong_account    /accounts/9000000003/transactions
calls by outcome:
  200  ok               8
  401  invalid_token    2
  403  consent_expired  1
  403  consent_revoked  1
  403  scope_missing    1
  403  wrong_account    1
rows of customer data handed over, by participant:
  LND-1: 7 calls, 374 rows
  LND-2: 1 calls, 1 rows
consents holding a raw token: 0
calls that read another customer's data and were allowed:
   none

The times are yours. Every call from steps 4 to 7 is there, refused or allowed, and the refused ones carry their reason. Customer 2 sees the two bad tokens because the path named their account, and customer 3 sees a call by consent 1 that tried to read their data and was refused. That second row is the one a regulator asks about. The 374 rows are 185 from the first lender run, 185 from the short consent, 2 from the wider consent and the two single balance rows. No consent holds a raw token. The last query is empty, which is what you want it to say.

Remove the account check. In a copy of the server, change the fourth question so that it ignores the consent’s customer:

sed 's/if customer_id is None or consent\["customer_id"\] != customer_id:/if customer_id is None:/' ob_server.py > ob_server_broken.py

Stop the server (Ctrl-C in its terminal), start python3 ob_server_broken.py, grant customer 2’s lender a token again, and call customer 3’s account with it.

python3 ob_consent.py grant --customer 2 --participant LND-1 --scopes transactions:read,balance:read --ttl 3600 --token-file data/lender1.token
python3 ob_lender.py --token-file data/lender1.token --account 9000000003
python3 ob_examine.py | tail -3

What to look for: the call returns 200 with 10 transactions, ₦142,420.08 in and ₦7,756.00 out, and a balance of 17,033,353 kobo, none of it customer 2’s. Every earlier test still passes, because each used one customer. The last query now lists calls with the consent’s customer (2) and the customer read (3). The list has two rows, one for the transactions call and one for the balance call. Your consent ids will differ with what you ran before, but the list will not be empty. Then restore the original server, and write the test that would have caught it before release.

ARTEFACT Write a data-access partner review ~50 MIN
YOU PRODUCEData-access partner review

Template

# Data-access partner review: <partner> (<participant id>)
Product owner · Security · Compliance · Date · Signs: Data protection officer
Decision needed: <which scopes, for which customers, for how long>

## 1. The request
Partner, product it serves, the customer data it asks for, how many customers.

## 2. Data asked for, against what the use case needs
Purpose in the customer's words: <purpose>
| Scope or field | Asked? | Needed for the purpose? | Decision |
|---|---|---|---|

## 3. The consent the customer gives
What the customer sees: <purpose, scopes, end date>
How the customer revokes: <where>. What the partner sees next: <status, reason code>

## 4. Access scope and expiry
Account or customers covered: <...>. Scopes granted: <...>.
Consent ends: <length>, and what the partner must do to continue.

## 5. Security and logging checks
| Check | Evidence | Result |
|---|---|---|

## 6. What this review cannot see
- <unverified item> — <who would settle it>

## 7. Decision
Approve / approve with conditions / decline: <decision>
Conditions: <...>. Review again by: <date>.
How this review could be wrong, and what would show it: <...>

Signed: <data protection officer> · <date>
WORKED EXAMPLE

At a real bank the product owner for the API writes this review with security and compliance, and the data protection officer signs it. At Northmere Bank, Ademola, who leads digital channels, is that product owner and wrote it with Larissa, who builds the consent service. Date: 20 November 2026. Decision needed: which scopes the first lender may hold.

Request. One lender, registered in the lab as LND-1, wants to read account 9000000002, the lab’s stand-in, for a working-capital loan, and asks for all three scopes.

Data against need. The purpose is ‘Affordability check for a working-capital loan application’. The check needs 90 days of dated amounts and the balance. transactions:read returned 185 transactions for 2026-04-01 to 2026-06-30, ₦4,743,619.00 in and ₦4,688,715.28 out, net ₦54,903.72, six fields each, in two requests (100 and 85 rows). balance:read returned 11,714,513 kobo, ₦117,145.13. counterparty:read was asked ‘in case’, and the lender’s sums never use the other bank’s code. Declined.

Consent. The customer sees the purpose, the two scopes and the end date, and revokes in the banking app. The lab shows the next call answered 403 consent_revoked.

Scope and expiry. The consent names one customer, so one account. It ends after 3600 seconds; the lab’s 90-day cap is invented.

Checks. The lab printed 403 wrong_account for customer 3’s account, and 0 consents holding a raw token. The cross-customer query printed none. All 14 calls were logged with reasons.

Not verified. Registry and tier rules, and any log retention duty: the chapter did not read the CBN text. The lab server also lets a caller choose any date range, and no consent limits it.

Decision. Approve transactions:read and balance:read; decline counterparty:read. Net ₦54,903.72 is the route of money through a wallet, not earnings. If the log later shows more than 185 rows per run, our estimate of need is wrong.

Signed: the data protection officer.

Now you

A month later, a second lender, registered in the lab as LND-2, writes to you, the product owner for Northmere’s open banking API. It holds balance:read today, to check a balance before it sets a card limit. It now asks for transactions:read over the last 12 months, saying that ‘it will refine limits’. You are writing the review with security and compliance, and the data protection officer signs it.

Use the lab. Step 5 shows LND-2 refused at the door with scope_not_allowed_for_participant, allowed ['balance:read'], and then scope_missing on a transactions call. Step 8 shows LND-2 made 1 call and received 1 row. Set what a card limit needs against what 12 months of transactions would reveal, using the 90-day figures in step 4 (the lab did not measure 12 months). Say whether the lender’s registration should change, what consent length you would allow, and what you could not check. The data protection officer reads it to decide whether to widen LND-2’s registration.

Self-check

DECIDE

Ademola and Larissa have a lender asking for transaction access for a working-capital product, and a regime whose go-live is unconfirmed. The CBN framework and guidelines exist. Larissa's team could build a consent service and access log in a quarter. Legal says the bank is not yet obliged to offer access. What should the bank do first?

READING
  1. DOC
    Circular on the Regulatory Framework on Open Banking in Nigeria (CBN, 2021) Central Bank of Nigeria, 2021

    The CBN's own circular: the data categories, the participant tiers and the framework's definitions. Read the categories and tiers first, because the chapter's table of them rests on summaries. The CBN site did not open when this chapter was written; the URL is the one the search results listed.

  2. DOC
    Operational Guidelines for Open Banking in Nigeria (CBN, March 2023) Central Bank of Nigeria, 2023

    The document that turns the framework into duties for API providers and consumers, with appendices on API standards and security. Read the consent, registry and audit sections and settle the questions this chapter marks as unconfirmed, such as who runs the registry. The search listing marked it confidential; check you have the final March 2023 version, not the 2022 exposure draft.

  3. POST
    Nigeria's open banking is still in the works (TechCabal) TechCabal, 2025

    A press report of October 2025 on the deferred launch. It is press, not the CBN, so read it for what was reported and then look for a CBN circular. Skip the commentary on fintech business models.

  4. DOC
    Regulatory: the CMA Order (Open Banking, UK) openbanking.org.uk

    The implementation entity's own page on the CMA Order 2017 and the roadmap it set. Read it for the history of how a competition remedy produced an API standard. Skip the later sections on newer services if you want the data half only.

  5. DOC
    Directive (EU) 2015/2366, Article 67 (PSD2) European Parliament and Council, 2015

    The article on account information services in its adopted form: explicit consent, limits on use and no contract with the bank. Read paragraph 2 closely. It is the original text, not the consolidated one. Read: Article 67.

  6. DOC
    Open Banking: Joint Resolution No 1 of 2020 (Banco Central do Brasil) CMN and Banco Central do Brasil, 2020

    The Brazilian regulation in English on the central bank's site. Read the scope and consent articles and compare how a regulator names participants with how Nigeria groups them in tiers. Later amendments exist and are not in this file.

All companies and people in these examples are fictional. Any resemblance to a real business or person is unintended.

RECALL CARDS Tap to flip. They join your review deck when you mark the lesson complete.
NEXT: PCI DSS and keeping card data out of scope →