Updated Nov 27, 20268 min read

Build an Open Banking Consent and Reauthorization Backend

How to track bank connection consents through pending, active, expired and revoked, renew the 180 day authentication window before data access stops, handle revocation callbacks and sweeps safely, and run it on AWS or GCP.

Illustration for Build an Open Banking Consent and Reauthorization Backend

An open banking integration looks finished once the first bank connection returns transactions. The consent behind it keeps changing state: it is pending until the customer finishes at the bank, active for a limited time, revoked if the customer pulls it, and expired if nobody renews it.

Treating that as a status column and a calendar reminder works for a hundred connections and fails at ten thousand, where a missed renewal means a customer silently loses their data feed. This guide builds the consent service with states, a renewal window, idempotent callbacks and a daily sweep.

PieceWhat to decide
StatesPending, active, expired, revoked and superseded, with one active consent per customer and bank
ExpiryThe date after which the bank rejects requests without a fresh authentication, set from the callback and defaulting to the 180-day strong customer authentication window
RenewalA reminder before expiry, and a new consent that replaces the old one when it activates
CallbacksActivation and revocation arrive as retried webhooks, so each must be safe to apply twice
Data accessA single check that says whether a consent may be used right now
AuditWho granted, renewed or lost a consent, and when

The 180 days come from the amended regulatory technical standards: since July 2023 an account information provider may rely on the exemption from strong customer authentication only if the customer authenticated at first access and at least every 180 days after, as the EU delegated regulation 2022/2360 and the EBA final report describe. Banks and aggregators can end a consent sooner, which is why the expiry is taken from the provider when it is shorter.

How do you build it without a framework?

The schema carries the state, a unique state value for the bank round trip and a partial unique index that allows one active consent per customer and bank, and each transition is a single guarded statement so that a retried webhook cannot apply twice. Activation is a transaction that supersedes the previous active consent and turns the pending one on, guarded by status = 'pending' so the second delivery of the same callback finds nothing to update. The sweep is two statements, one that reminds and one that expires, each marking rows in the same statement that selects them, so that a rerun of the job after a crash does nothing twice. You also need a scheduler that survives restarts, a queue for the reminders and secrets for the provider credentials. Teams bring their own agents, and Encore provides the environments, the system context and the controls for those pieces.

Encore brings infrastructure from code, so the consent table, the reminder topic and the daily sweep are declared with the endpoints and created in your own AWS or GCP account on deploy. The AWS docs list Fargate, RDS and SNS with SQS, and the GCP docs list Cloud Run, Cloud SQL and Pub/Sub.

Application code passes through Encore and infrastructure guardrails to resources provisioned in your own AWS or GCP account.

Set up the app

Get started
brew install encoredev/tap/encore &&
encore app create
Copy

Run in your terminal to get started locally.

~
$ encore app create banking --example=hello-world$ cd banking && mkdir -p consent/migrations

The service below starts a consent, activates it from the provider callback, applies revocations, answers whether a consent is usable and runs the daily sweep:

// consent/consent.go package consent import ( "context" "crypto/rand" "encoding/hex" "errors" "strings" "time" "encore.dev/beta/errs" "encore.dev/cron" "encore.dev/pubsub" "encore.dev/rlog" "encore.dev/storage/sqldb" ) var db = sqldb.NewDatabase("consent", sqldb.DatabaseConfig{Migrations: "./migrations"}) type Expiring struct { ConsentID int64 `json:"consent_id"` UserID string `json:"user_id"` } var expiring = pubsub.NewTopic[*Expiring]("consent-expiring", pubsub.TopicConfig{ DeliveryGuarantee: pubsub.AtLeastOnce, }) type StartParams struct { UserID string `json:"user_id"` Provider string `json:"provider"` } type StartResponse struct { State string `json:"state"` } // Start creates a pending consent and returns the state value to send to the bank. // //encore:api public method=POST path=/consents func Start(ctx context.Context, p *StartParams) (*StartResponse, error) { if strings.TrimSpace(p.UserID) == "" || strings.TrimSpace(p.Provider) == "" { return nil, &errs.Error{Code: errs.InvalidArgument, Message: "user_id and provider are required"} } b := make([]byte, 16) if _, err := rand.Read(b); err != nil { return nil, err } state := hex.EncodeToString(b) _, err := db.Exec(ctx, ` INSERT INTO consents (user_id, provider, state) VALUES ($1, $2, $3)`, p.UserID, p.Provider, state) if err != nil { return nil, err } return &StartResponse{State: state}, nil } type CallbackParams struct { State string `json:"state"` ProviderConsentID string `json:"provider_consent_id"` ProviderExpiresAt *time.Time `json:"provider_expires_at,omitempty"` } // Callback activates the consent after the customer finishes at the bank. // A repeated callback finds no pending row and changes nothing. // //encore:api public method=POST path=/consents/callback func Callback(ctx context.Context, p *CallbackParams) error { tx, err := db.Begin(ctx) if err != nil { return err } defer tx.Rollback() var id int64 var userID, provider string err = tx.QueryRow(ctx, ` SELECT id, user_id, provider FROM consents WHERE state = $1 AND status = 'pending' FOR UPDATE`, p.State).Scan(&id, &userID, &provider) if errors.Is(err, sqldb.ErrNoRows) { return nil } if err != nil { return err } // The new consent replaces any active one for the same customer and bank. if _, err := tx.Exec(ctx, ` UPDATE consents SET status = 'superseded' WHERE user_id = $1 AND provider = $2 AND status = 'active'`, userID, provider); err != nil { return err } // Banks can end a consent sooner than the 180-day authentication window, so the earlier date wins. if _, err := tx.Exec(ctx, ` UPDATE consents SET status = 'active', provider_consent_id = $2, granted_at = now(), expires_at = LEAST(now() + interval '180 days', COALESCE($3::timestamptz, now() + interval '180 days')) WHERE id = $1`, id, p.ProviderConsentID, p.ProviderExpiresAt); err != nil { return err } return tx.Commit() } type RevokedParams struct { ProviderConsentID string `json:"provider_consent_id"` } //encore:api public method=POST path=/consents/revoked func Revoked(ctx context.Context, p *RevokedParams) error { _, err := db.Exec(ctx, ` UPDATE consents SET status = 'revoked' WHERE provider_consent_id = $1 AND status = 'active'`, p.ProviderConsentID) return err } type UsableResponse struct { Usable bool `json:"usable"` ExpiresAt *time.Time `json:"expires_at,omitempty"` } // Usable is the one check that data pulls call before touching the bank. // //encore:api private method=GET path=/consents/usable/:userID/:provider func Usable(ctx context.Context, userID, provider string) (*UsableResponse, error) { var exp time.Time err := db.QueryRow(ctx, ` SELECT expires_at FROM consents WHERE user_id = $1 AND provider = $2 AND status = 'active' AND expires_at > now()`, userID, provider).Scan(&exp) if errors.Is(err, sqldb.ErrNoRows) { return &UsableResponse{Usable: false}, nil } if err != nil { return nil, err } return &UsableResponse{Usable: true, ExpiresAt: &exp}, nil } type SweepResponse struct { Reminded int `json:"reminded"` Expired int `json:"expired"` } // Sweep expires lapsed consents and queues a reminder for those ending within 14 days. // //encore:api private func Sweep(ctx context.Context) (*SweepResponse, error) { var out SweepResponse if err := db.QueryRow(ctx, ` WITH gone AS ( UPDATE consents SET status = 'expired' WHERE status = 'active' AND expires_at <= now() RETURNING 1 ) SELECT count(*)::int FROM gone`).Scan(&out.Expired); err != nil { return nil, err } rows, err := db.Query(ctx, ` UPDATE consents SET reminded_at = now() WHERE status = 'active' AND reminded_at IS NULL AND expires_at <= now() + interval '14 days' RETURNING id, user_id`) if err != nil { return nil, err } var due []*Expiring for rows.Next() { var e Expiring if err := rows.Scan(&e.ConsentID, &e.UserID); err != nil { rows.Close() return nil, err } due = append(due, &e) } rows.Close() for _, e := range due { if _, err := expiring.Publish(ctx, e); err != nil { return nil, err } } out.Reminded = len(due) return &out, nil } var _ = cron.NewJob("consent-sweep", cron.JobConfig{ Title: "Expire lapsed consents and send renewal reminders", Schedule: "0 6 * * *", Endpoint: Sweep, }) var _ = pubsub.NewSubscription(expiring, "renewal-reminder", pubsub.SubscriptionConfig[*Expiring]{ Handler: func(ctx context.Context, e *Expiring) error { rlog.Info("send renewal reminder", "consent", e.ConsentID, "user", e.UserID) return nil }, })
-- consent/migrations/1_create_consents.up.sql CREATE TABLE consents ( id BIGSERIAL PRIMARY KEY, user_id TEXT NOT NULL, provider TEXT NOT NULL, state TEXT NOT NULL UNIQUE, provider_consent_id TEXT UNIQUE, status TEXT NOT NULL DEFAULT 'pending' CHECK (status IN ('pending', 'active', 'expired', 'revoked', 'superseded')), granted_at TIMESTAMPTZ, expires_at TIMESTAMPTZ, reminded_at TIMESTAMPTZ, created_at TIMESTAMPTZ NOT NULL DEFAULT now() ); CREATE UNIQUE INDEX consents_one_active ON consents (user_id, provider) WHERE status = 'active'; CREATE INDEX consents_expiry_idx ON consents (expires_at) WHERE status = 'active';

encore run starts Postgres locally and applies the migration, so the start, callback and revocation flow can be driven with curl, and the sweep is tested by calling its endpoint from the local development dashboard because cron jobs do not run locally. The database docs cover transactions and migrations, and the cron docs cover schedules, which are managed by the Encore platform.

Deploying follows Connect your cloud account and a push, and the RDS or Cloud SQL database, the topic and the schedule are created in your account. The reminder subscriber is the place to call your email or push provider, and an AI coding agent adding a second reminder at seven days edits the query and the handler in one change that it runs locally first.

Best fit: Fintech teams that aggregate bank data and want consent states, renewals and revocations handled in a service that runs in their own AWS or GCP account.

What should you check before going live?

Verify the signature on every webhook from your aggregator or bank before the callback and revocation endpoints change anything. Confirm with them whether the consent end date arrives in the callback and which revocation events it sends, since the code above takes the provider date when it is sooner than the 180-day authentication window. Keep access tokens and refresh tokens encrypted and out of the consents table, and decide how long transaction data is kept after a consent is revoked or expires. Legal counsel decides what your authorization with the bank requires, and the service only records and enforces the dates.

Frequently asked questions

Does PSD2 cap an open banking consent at 180 days?

No. The 180 days are the strong customer authentication exemption window under the amended regulatory technical standards, not a cap on consent duration. Since July 2023 an account information provider may rely on the exemption only if the customer authenticated at first access and at least every 180 days after, as the [EU delegated regulation 2022/2360](https://eur-lex.europa.eu/eli/reg_del/2022/2360/oj/eng) describes. Banks and aggregators can end a consent sooner, and requests are rejected until the customer authenticates again once that window has passed.

How do I remind customers to reauthorize a bank connection?

Store an expires_at on each consent, run a daily job that selects active consents expiring within a set number of days and not yet reminded, and mark them reminded in the same statement before publishing a reminder event. The reminder links to a new consent flow, and activating the new consent supersedes the old one.

What should happen when the bank revokes a consent?

Mark the consent revoked as soon as the callback arrives, stop scheduled data pulls for it and keep the stored data according to your retention policy. The callback should be idempotent, since banks and aggregators retry webhooks.

How do I run an open banking consent service in my own AWS account?

Build it with Encore, declaring the database, the reminder topic and the daily cron job in code, and deploy it to your own AWS or GCP account. encore run starts Postgres locally, so the activation and sweep queries can be tested before deploying.

Deploy to your cloud on AWS and Google Cloud
without managing infrastructure

Encore lets developers and agents define application infrastructure directly in code, then automatically provisions it from local development to production in your AWS or GCP account.

~/orders — claude
Claude Code
Claude Code v2.1.180Opus 5.5~/orders