<!-- mobian-agent-page publisher="dailydev" canonical="https://daily.dev/posts/migrating-multi-tenant-auth-to-oauth-2-1-notes-decisions-and-a-pragmatic-roadmap-ldihnumvc" -->

---
title: Migrating Multi‑Tenant Auth to OAuth 2.1: Notes,...
description: A detailed technical account of migrating a multi-tenant authentication system from a custom dual-token flow to OAuth 2.1. Covers the rationale for adopting...
canonical: https://daily.dev/posts/migrating-multi-tenant-auth-to-oauth-2-1-notes-decisions-and-a-pragmatic-roadmap-ldihnumvc
twitter:card: summary_large_image
twitter:site: @dailydotdev
og:type: website
og:site_name: daily.dev
og:title: Migrating Multi‑Tenant Auth to OAuth 2.1: Notes, Decisions, and a Pragmatic Roadmap | daily.dev
og:description: A detailed technical account of migrating a multi-tenant authentication system from a custom dual-token flow to OAuth 2.1. Covers the rationale for adopting...
og:url: https://daily.dev/posts/migrating-multi-tenant-auth-to-oauth-2-1-notes-decisions-and-a-pragmatic-roadmap-ldihnumvc
og:image: https://api.daily.dev/og/posts/LDiHNumVc.png
og:image:alt: Migrating Multi‑Tenant Auth to OAuth 2.1: Notes, Decisions, and a Pragmatic Roadmap
og:image:width: 1200
og:image:height: 630
og:locale: en
---

> ## Documentation Index
> Fetch the complete documentation index at: https://daily.dev/llms.txt
> Use this file to discover all available pages before exploring further.

# Migrating Multi‑Tenant Auth to OAuth 2.1: Notes, Decisions, and a Pragmatic Roadmap

**[goker](https://daily.dev/sources/3i0pddhjif0hiyiyxcoh2)** · [@gokerdev](https://daily.dev/gokerdev) · 5 min read · 1 upvotes · 0 comments

## Summary

A detailed technical account of migrating a multi-tenant authentication system from a custom dual-token flow to OAuth 2.1. Covers the rationale for adopting OAuth 2.1's modern security defaults (PKCE, no implicit flow, refresh-token rotation), implementing the Backend-for-Frontend (BFF) pattern with Next.js to keep tokens server-side, and maintaining RTK Query Codegen compatibility through adapters. Includes practical migration steps, multi-tenant requirements (tenant-scoped authorization, isolation, delegation), common pitfalls encountered, and a phased rollout strategy with canary testing.

## Content

> “I sat down to write a blog post. I found a systemic bug. While fixing it, I reopened the auth code, and the work circled back to the unfinished mechanism—suddenly I was migrating to **OAuth 2.1**.”

This post consolidates the technical notes I’ve been jotting down over the **last month**. It outlines how I’m aligning a **multi-tenant** authentication layer with OAuth 2.1, the architectural decisions behind it, the practical pitfalls, and a short-term roadmap. Tools in the loop: Gemini, ChatGPT, and Cursor—what began as internal docs became the basis for this write-up.

---

## Where We Started and How We Got Here

- **Initial state:** The system did **not** run on OAuth 2.0. It used a **custom, dual-token** flow.
- **Step 1 — Documentation pass:** We first rewrote internal docs using **OAuth 2.0** terminology (flows, scopes, redirect URIs, PKCE, etc.) to establish common ground.
- **Step 2 — Alignment:** We then updated those docs to **OAuth 2.1**, adopting modern best practices (e.g., removal of implicit flow, PKCE by default).
- **Step 3 — Migration:** Once the approach was clear, we kicked off the **migration**: BFF pattern, cookie-based sessions, moving admin modules to Next.js, and a thin adapter to keep RTK Query Codegen viable.

---

## Why OAuth 2.1

OAuth 2.1 consolidates scattered 2.0 best practices under a modern, opinionated baseline:

- **PKCE by default:** Reduces token interception risk for public clients.
- **No implicit flow:** Removes fragile browser token handling.
- **Standardized hygiene:** Short-lived access tokens, refresh-token rotation, and scope discipline are treated as table stakes.
- **Clarity > ambiguity:** Fewer edge cases to interpret—especially helpful for multi-tenant boundaries.

> TL;DR: 2.1 turns many “optional but required in practice” 2.0 patterns into defaults, reducing attack surface and cognitive load.

---

## Architectural Decision: BFF Is a Must

With OAuth 2.1, the **Backend-for-Frontend (BFF)** pattern became the obvious boundary:

- **Why:** Avoid carrying access tokens in the browser; rely on **HttpOnly, Secure, SameSite** cookies and server-side session state to shrink XSS/CSRF exposure.
- **Impact:** My **Vite + React** SPA templates no longer fit. I’m moving administrative surfaces to **Next.js**, centralizing auth/session in middleware that plays nice at the edge.

> BFF is not “just a proxy.” It’s a smart boundary that simplifies authorization decisions and keeps token lifecycles server-side.

---

## Client Layer and RTK Codegen

- **Goal:** Preserve the existing **RTK Query Codegen** loop.
- **Approach:** Insert a thin adapter so the client speaks to BFF-exposed endpoints while Codegen remains blissfully unaware.
- **Risk:** Silent breakage if the OpenAPI schema drifts. **Mitigation:** SemVer + automated contract tests in CI.

---

## Multi-Tenant Requirements (Recap)

1. **Tenant-scoped authorization:** Carry a `tenant_id` claim; resolve permissions (RBAC/ABAC) within tenant context.
2. **Isolation:** Track tokens, sessions, and rate limits per tenant.
3. **Delegation:** Provide auditable impersonation for tenant admins.
4. **Self-service onboarding:** Invites, domain verification, and billing hooks.
5. **Observability:** Central metrics for failures, flow distribution, MFA adoption, anomalies.

---

## Migration Plan

**A. Preparation**
- Inventory existing env/secrets, proxies, and any 2.0-like assumptions.
- Validate all clients and redirect URIs; enforce **PKCE**.
- Turn on **refresh-token rotation**; shorten access-token TTLs.

**B. BFF Layer**
- Session cookie: **HttpOnly + Secure + SameSite=Lax/Strict**.
- CSRF protection: **double-submit** or equivalent.
- Token exchange + **session re-issue** logic with robust logging.

**C. Authorization**
- Simplify scope/permission mapping; include tenant-scoped claims.
- Policy gates at the endpoint level (OPA/Cedar-style) or lean RBAC.

**D. Client Adaptations**
- Move admin modules to **Next.js**; provide a lightweight SDK for SPA surfaces to call the BFF.
- Keep **RTK Codegen** via the adapter; wire up contract tests.

**E. Rollout / Gradual Cutover**
- Enable 2.1 flows for **canary tenants** first.
- Watch error rates, mean login time, refresh success, and anomaly spikes.
- Sunset legacy flows incrementally.

---

## Issues I Hit (and How I Addressed Them)

- **“No tokens in the browser—how do I authorize?”** → Move the session to the **BFF**; the client talks only to session-bound endpoints.
- **“Will mixing CSR/SSR hurt?”** → SSR/ISR for critical surfaces, CSR for the rest; lean on edge cache + short TTLs.
- **“Codegen keeps breaking.”** → Contract tests + OpenAPI diff gates in CI.

---

## Personal Log: Code, Renovation, and Energy Management

The **last month** has been intense on code; what you’re seeing here is maybe **25%** of it. I poked at **Flutter**, pushed auth/blog forward, and—oddly enough—spent a lot of time on **home renovation**. If you’re curious: [Instagram Reels](https://www.instagram.com/reel/DPdo8FZjNND/).

> Over the last decade, I’ve invested a lot in tools (saws, drills, etc.). Still no workshop—yet. With the rains, renovation paused and I drifted back to code.

Motivation fluctuates. I’ve been between jobs for a while; sometimes I **over-engineer** hoping the codebase will be ready if I find an investor—or maybe I’m just indulging myself. Honest developer diary stuff.

---

## Academic Track

I’m waiting on a decision for a journal submission. If graduation slips this term, the **PhD** chapter may close. A second paper was on deck—but energy is finite.

---

## Collaboration & Work

I’m open to freelance contributions. Productization, multi-tenant architectures, **Next.js BFF**, **OAuth 2.1** migrations, **RTK Query/Codegen**, and end-to-end delivery from design to deploy—if you need help, feel free to reach out.

---

## Short-Term Roadmap

- [ ] Next.js BFF skeleton + session plumbing
- [ ] Authorization Code with **PKCE** end-to-end
- [ ] Refresh-token rotation + short TTLs
- [ ] RTK Codegen adapter + contract tests
- [ ] Tenant-scoped policy layer
- [ ] Canary rollout + metrics dashboard

---

## Closing

“Before autumn fully sets in, I’m still a leaf in the wind.” Even so, the direction is clear: a secure, observable, product-ready identity layer. This post is a note to self—and hopefully a small guide for anyone setting off on a similar path.

**P.S.** This also marks my **first year on daily.dev**. I haven’t built much reputation there yet, but here’s to doing better over the next year. 🙂 Thanks for reading.

---

Tags: [#security](https://daily.dev/tags/security), [#architecture](https://daily.dev/tags/architecture), [#authentication](https://daily.dev/tags/authentication), [#nextjs](https://daily.dev/tags/nextjs), [#oauth](https://daily.dev/tags/oauth)

[View this post on daily.dev](https://daily.dev/posts/migrating-multi-tenant-auth-to-oauth-2-1-notes-decisions-and-a-pragmatic-roadmap-ldihnumvc)

```json
{"@context":"https://schema.org","@graph":[{"@type":"Organization","@id":"https://daily.dev/#organization","name":"daily.dev","url":"https://daily.dev","logo":{"@type":"ImageObject","url":"https://daily.dev/apple-touch-icon.png","width":180,"height":180},"sameAs":["https://twitter.com/dailydotdev","https://github.com/dailydotdev","https://www.linkedin.com/company/daily-dev-ltd"]},{"@type":"WebSite","@id":"https://daily.dev/#website","url":"https://daily.dev","name":"daily.dev","publisher":{"@id":"https://daily.dev/#organization"},"potentialAction":{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https://daily.dev/search?q={search_term_string}"},"query-input":"required name=search_term_string"}}]}
{"@context":"https://schema.org","@type":"DiscussionForumPosting","mainEntityOfPage":"https://daily.dev/posts/migrating-multi-tenant-auth-to-oauth-2-1-notes-decisions-and-a-pragmatic-roadmap-ldihnumvc","headline":"Migrating Multi‑Tenant Auth to OAuth 2.1: Notes, Decisions, and a Pragmatic Roadmap","text":"A detailed technical account of migrating a multi-tenant authentication system from a custom dual-token flow to OAuth 2.1. Covers the rationale for adopting OAuth 2.1's modern security defaults (PKCE, no implicit flow, refresh-token rotation), implementing the Backend-for-Frontend (BFF) pattern with Next.js to keep tokens server-side, and maintaining RTK Query Codegen compatibility through adapters. Includes practical migration steps, multi-tenant requirements (tenant-scoped authorization, isolation, delegation), common pitfalls encountered, and a phased rollout strategy with canary testing.","url":"https://daily.dev/posts/migrating-multi-tenant-auth-to-oauth-2-1-notes-decisions-and-a-pragmatic-roadmap-ldihnumvc","datePublished":"2025-10-10T20:15:53.595Z","dateModified":"2025-10-10T20:16:16.809Z","author":{"@type":"Person","name":"goker","url":"https://daily.dev/gokerdev","image":"https://media.daily.dev/image/upload/s--gnfLx12d--/f_auto/v1753649622/avatars/avatar_3I0pddhJiF0HIYiyxcoH2?_a=BAMClqZW0","description":"Computer Engineer (PhDc) building precision AI tools. Fusing systems with visual design.","interactionStatistic":{"@type":"InteractionCounter","interactionType":{"@type":"EndorseAction"},"userInteractionCount":80}},"image":"https://media.daily.dev/image/upload/s--l02rIRv0--/f_auto/v1760127356/posts/LDiHNumVc?_a=BAMAK+ZW0","interactionStatistic":[{"@type":"InteractionCounter","interactionType":{"@type":"LikeAction"},"userInteractionCount":1},{"@type":"InteractionCounter","interactionType":{"@type":"CommentAction"},"userInteractionCount":0}],"isPartOf":{"@type":"WebPage","url":"https://daily.dev/sources/3i0pddhjif0hiyiyxcoh2","name":"goker"}}
{"@context":"https://schema.org","@type":"BreadcrumbList","itemListElement":[{"@type":"ListItem","position":1,"name":"Home","item":"https://daily.dev"},{"@type":"ListItem","position":2,"name":"goker","item":"https://daily.dev/sources/3i0pddhjif0hiyiyxcoh2"},{"@type":"ListItem","position":3,"name":"Migrating Multi‑Tenant Auth to OAuth 2.1: Notes, Decisions, and a Pragmatic Roadmap"}]}
```

