惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

月光博客
月光博客
L
LangChain Blog
Jina AI
Jina AI
WordPress大学
WordPress大学
人人都是产品经理
人人都是产品经理
S
Secure Thoughts
T
The Exploit Database - CXSecurity.com
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
博客园 - 聂微东
小众软件
小众软件
Apple Machine Learning Research
Apple Machine Learning Research
C
Cyber Attacks, Cyber Crime and Cyber Security
Project Zero
Project Zero
T
Threat Research - Cisco Blogs
量子位
G
GRAHAM CLULEY
腾讯CDC
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
C
CERT Recently Published Vulnerability Notes
The Hacker News
The Hacker News
C
Cisco Blogs
Scott Helme
Scott Helme
Spread Privacy
Spread Privacy
宝玉的分享
宝玉的分享
V
V2EX
博客园 - 三生石上(FineUI控件)
T
Tor Project blog
P
Proofpoint News Feed
雷峰网
雷峰网
D
Darknet – Hacking Tools, Hacker News & Cyber Security
V
Vulnerabilities – Threatpost
PCI Perspectives
PCI Perspectives
博客园_首页
L
LINUX DO - 最新话题
IT之家
IT之家
有赞技术团队
有赞技术团队
博客园 - Franky
Hacker News: Ask HN
Hacker News: Ask HN
Last Week in AI
Last Week in AI
The Cloudflare Blog
Exploit-DB.com RSS Feed
Exploit-DB.com RSS Feed
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
美团技术团队
博客园 - 【当耐特】
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
Security Archives - TechRepublic
Security Archives - TechRepublic
L
LINUX DO - 热门话题
AWS News Blog
AWS News Blog
S
Security Affairs
T
Tailwind CSS Blog

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant Common SOC 2 Failures (Real World) Stop Vibe-Checking Your AI App: A Practical Guide to Evals How to Use SonarQube and SonarScanner Locally to Level Up Your Code Quality Your Next To-Do App Is Dead — I Replaced Mine with an OpenClaw AI Sign a Nostr event in 60 lines of Python using coincurve — no nostr-sdk, no nbxplorer, no rust toolchain ITGC Audit Explained Like You’re in Big 4 Patch Tuesday abril 2026: Microsoft parcha 163 vulnerabilidades y un zero-day en SharePoint Stop scraping everything: a better way to track competitor price changes Listing on MCPize + the Official MCP Registry while routing payments OUTSIDE the marketplace — how I kept 100% of my x402 revenue Building an AI-Powered Risk Intelligence System Using Serverless Architecture Why We Ripped Function Overloading Out of Our AI Toolchain Testing AI-Generated Code: How to Actually Know If It Works SaaS Churn Is Killing Your Business. Here Is What to Do About It (Without a Support Team) The Speed of AI Is No Longer Linear - And Self-Improving Models Are Why How to Implement RBAC for MCP Tools: A Practical Guide for Engineering Teams From Standard Quote to Persuasive Proposal: AI Automation for Arborists I built a CLI that scaffolds complete multi-tenant SaaS apps Axios CVE-2025–62718: The Silent SSRF Bug That Could Be Hiding in Your Node.js App Right Now The dashboard that ended our friendship Data Pipelines Explained Simply (and How to Build Them with Python) The Hidden Cost of AI Systems Nobody Talks About. undefined vs undeclared, and how typeof behaves Switching from file-based jobs to NATS/Kafka in Rust without changing code io_uring Adventures: Rust Servers That Love Syscalls Why Agentic AI is Killing the Traditional Database The POUR principles of web accessibility for developers and designers Quantum Neural Network 3D — A Deep Dive into Interactive WebGL Visualization How To Install Caveman In Codex On macOS And Windows Automation Pipeline Reliability: Why Your Workflow Breaks When Nobody Is Watching I Built an 'Open World' AI Coding Agent — It Works From ANY Folder From Freelancing to Product: A Tech Service Company's SaaS Transformation China's AI Giants: Adding Tencent Hunyuan & ByteDance Doubao to AI University (74 Providers) On the Vibe Coders and Their Lies clerk: Auto-Summarize Your Claude Code Sessions AI Weekly — 2026/04/10–04/17 | The Model Lockdown Is Here, but the Toolchain Is the Real Battleground AI 週報 — 2026/04/10–2026/04/17 模型封鎖潮來了,但工具鏈才是真戰場 Maybe this is how Open-Source apps are born... 🚀 Fine-Tune LLMs with LoRA and QLoRA: 2026 Guide tRPC v11 + Next.js App Router: End-to-End Type Safety Without the Boilerplate ShadCN UI in 2026: Why I Stopped Installing Component Libraries and Started Owning My Components SaaS Billing in React Server Components: Stripe + Supabase Without a Single `useEffect` Join our DEV Weekend Challenge — $1,000 in Prizes Across TEN winners! Submissions Due April 20 at 6:59 AM UTC. Implementing FSRS Spaced Repetition in Flutter + Supabase — Adding Memory Science to an AI Learning App "I Texted My Localhost From the Train — Claude Code Fixed the Bug Before I Got Home" I Built a Sales Prep AI and It Went Deeper Than Expected Design to Code #2: One JSON, Eleven Outputs Solving the 100M-Row Problem: A Summary Table Pattern for High-Volume Push Notification Logs Flutter Web With Wasm: What Actually Changes For Developers I Built 50 Royalty-Free Soundtracks for My Side Project in a Weekend Using AI Music Generation The Vibe Coding Security Checklist: 7 Things to Check Before You Ship Stop Letting Googlebot Guess Fix Your React App's SEO Right Desconstruindo o Streaming do LinkedIn: Como Criar um Engine de Extração de Vídeo de Alta Performance com HLS e FFmpeg (EDA Part-1) EDA (Exploratory Data Analysis) Explained With Real Life — Why Looking at Your Data Is the Most Important Step in Machine Learning Brand Relationship Management at Scale: Our 4-Touch Outreach System for 200+ Brands Why String.fromEnvironment() Might Return an Empty String in Dart JGuardrails 1.0.0 — Hardening Java LLM Apps Against Jailbreaks, Toxicity, and Prompt Injection Plan and Schedule a Full Week of Threads Content From One Claude Conversation Coding Cat Oran Ep3, Five Tables Changed Everything Updated: BFF Pattern I'm done watching freelancers get buried by 200 proposals. So I'm building the alternative. This is my first post BFS Algorithm in Java Step by Step Tutorial with Examples Tracking LLM Pricing Monthly: An Open Dataset for 22 AI Models How We Measure Content ROI on a Comparison Site: Revenue Attribution Without Perfect Data Introducing Nova AI Ops: The AI-Native Operating System for SRE Teams I built a free desktop video downloader for Windows — Grabbit How Talkie OCR Helps Vision-Impaired & Dyslexic Users Read the World Around Them VRCFaceTracking安装和iPhone面捕配置教程,有bug Even CrowdStrike Can't See Your Agents The Automation Gold Rush: What n8n Workflows and Claude Are Opening Up for Developers Right Now
Kinde Is Missing from Mastra's Auth Lineup, So I Built the Provider
Shola Jegede · 2026-06-22 · via DEV Community

If you're building a SaaS AI agent product and you're already on Kinde, you already know the problem.

Mastra is the TypeScript-first AI agent framework. It ships with official auth providers for Clerk, Auth0, Supabase, Firebase, WorkOS, and Better Auth. Kinde is not on that list.

The obvious question is why not reach for one of those providers, since Auth0 is already there.

Most developers who choose Kinde rely on far more than its login. Kinde ships with the organizational structures, permission systems, and monetization tools that products actually need, bringing auth, billing, feature flags, and multi-tenancy together in one platform. If you're building a B2B SaaS product on Kinde, you're using Kinde orgs to segment your customers, Kinde billing to manage subscriptions, and Kinde feature flags to gate features by plan. Switching to Auth0 or Clerk to support a Mastra agent would mean rebuilding all of that elsewhere, which is not a real option.

That gap is the problem. You need Kinde to work with Mastra, and until now there was no clean way to connect them.

That's why I built mastra-auth-kinde.

What Mastra's auth system actually does

When you add an auth provider to Mastra, it protects two things at once: all your API routes (/api/agents/*, /api/workflows/*, and so on) and your Mastra Studio UI. Every request to a protected route goes through your provider before it reaches anything else.

You extend Mastra's MastraAuthProvider base class and implement two methods:

  • authenticateToken(token, request) verifies the JWT and returns the decoded user, or null if it fails
  • authorizeUser(user, request) returns true to let the request through, or false for a 403

Mastra handles everything else: extracting the Bearer token from the Authorization header, calling your methods in order, and storing the verified user in the request context so your agents and tools can access it.

Why Kinde specifically

Beyond the billing and org story above, a few things make Kinde the right fit for agent developers in particular.

First, Kinde's org model maps directly to multi-tenancy, so each customer gets isolated data and configuration without you building it. Each Kinde organization is a tenant, and the org_code claim on every token tells you exactly which org the user belongs to. For a multi-tenant agent, one that serves different customers on the same infrastructure, this is exactly what you need.

Second, machine-to-machine authentication comes standard rather than as an expensive add-on. AI agents frequently need to run background jobs, scheduled workflows, and nightly pipelines with no human user in the loop. Kinde handles this natively with client credentials tokens, and this provider handles those too, which I cover below.

Third, the free tier is usable for real products, including 10,500 monthly active users, unlimited organizations, and all authentication methods including SSO. You can build a real multi-tenant agent product without paying anything until you're at scale.

Installation

npm install github:sholajegede/mastra-auth-kinde

You also need @mastra/core if you don't already have it:

npm install @mastra/core

Step 1 — Basic setup

Wire the provider into your Mastra instance:

import { Mastra } from '@mastra/core'
import { MastraAuthKinde } from 'mastra-auth-kinde'

export const mastra = new Mastra({
  server: {
    auth: new MastraAuthKinde({
      domain: 'https://yourapp.kinde.com',
    }),
  },
})

Or use environment variables:

KINDE_DOMAIN=https://yourapp.kinde.com
KINDE_AUDIENCE=https://api.yourapp.com  # optional — see the audience section below

export const mastra = new Mastra({
  server: {
    auth: new MastraAuthKinde(),
  },
})

Once this is in place, every request to /api/* needs a valid Kinde access token in the Authorization: Bearer <token> header. Unauthenticated requests get a 401, and requests that fail the authorization check get a 403.

Step 2 — User token authentication

A standard Kinde user access token carries these claims:

iss, sub, aud, azp, exp, iat, jti, scp

The provider verifies the token against Kinde's JWKS endpoint, validates the issuer and expiry, and checks the audience claim if you have the option configured.

Kinde's JWKS endpoint sits at /.well-known/jwks with no .json extension, even though the common assumption is /.well-known/jwks.json. Verify it against your tenant's discovery document before assuming:

curl -s https://yourapp.kinde.com/.well-known/openid-configuration | jq .jwks_uri
# "https://yourapp.kinde.com/.well-known/jwks"

The provider handles this correctly out of the box.

The audience option

Only set audience (or KINDE_AUDIENCE) once you've registered and bound an API audience in the Kinde dashboard. A default Kinde user token carries an empty aud array, and any token with an empty aud will fail the audience check if the option is set.

new MastraAuthKinde({
  domain: 'https://yourapp.kinde.com',
  audience: 'https://api.yourapp.com', // only add this after binding an API audience in Kinde
})

Step 3 — M2M / system-actor support

In the standard agent setup, a human user logs in, the frontend gets a token, and that token is passed to the Mastra API, which works for user-facing agents. Real agent architectures also have background jobs, things like nightly workflows, scheduled pipelines, and cron tasks, running with no human attached.

Kinde handles this with machine-to-machine apps using the OAuth client credentials flow. The resulting token looks different from a user token:

{
  "aud": ["https://yourapp.kinde.com/api"],
  "azp": "your_client_id",
  "exp": 1234567890,
  "gty": ["client_credentials"],
  "iat": 1234567890,
  "iss": "https://yourapp.kinde.com",
  "org_code": "org_abc123",
  "scope": "read:users",
  "scp": [],
  "v": "2"
}

Two things to notice: there is no sub claim, and there is a gty claim set to ["client_credentials"]. That combination tells you this is a machine rather than a person.

The provider detects this and treats the token as a trusted system actor instead of rejecting it. You can check for it in your agent tools or route handlers:

import { isSystemActor } from 'mastra-auth-kinde'

const user = requestContext.get('user')

if (isSystemActor(user)) {
  // trusted background process — no human user attached
  console.log('running for org:', user.org_code)
}

So a nightly workflow can mint a Kinde M2M token, pass it to your Mastra API, and authenticate cleanly, with no human user required.

Step 4 — Org-based access control

If you're building a multi-tenant product where different organizations should only access their own agents and data, use allowedOrgCodes:

new MastraAuthKinde({
  domain: 'https://yourapp.kinde.com',
  allowedOrgCodes: ['org_abc123', 'org_def456'],
})

The provider checks the org_code claim on every token and rejects anything that doesn't match. This works for both user tokens (when org claims are enabled in Kinde) and M2M tokens, which carry org_code automatically when the app is org-scoped in Kinde.

On user tokens, org_code only appears once you've enabled org claims in the Kinde dashboard token customization settings, so if you decode a default user token and the claim is missing, that is a Kinde config step rather than a bug in the provider.

Step 5 — Edge deployment

The provider uses jose for JWT verification, which runs on Web Crypto and fetch, with no Node.js built-ins and no nodejs_compat flag needed on Cloudflare Workers.

This matters if you're planning to deploy your Mastra agent to the edge. Node-only JWKS libraries fail at build time on Workers with missing crypto, buffer, stream, http, https, events, and util. With jose, it builds clean and runs without any additional flags. This is the same approach Mastra's own Auth0 provider uses.

Putting it all together

Here's a full setup for a multi-tenant Mastra agent that supports both human users and background M2M workflows:

import { Mastra } from '@mastra/core'
import { Agent } from '@mastra/core/agent'
import { openai } from '@ai-sdk/openai'
import { MastraAuthKinde } from 'mastra-auth-kinde'

const supportAgent = new Agent({
  name: 'support-agent',
  instructions: 'You are a helpful support agent.',
  model: openai('gpt-4o-mini'),
})

export const mastra = new Mastra({
  agents: { supportAgent },
  server: {
    auth: new MastraAuthKinde({
      domain: process.env.KINDE_DOMAIN!,
      audience: process.env.KINDE_AUDIENCE,
      allowedOrgCodes: process.env.KINDE_ALLOWED_ORGS?.split(','),
    }),
  },
})

On the frontend, get the access token from the Kinde SDK and pass it as a Bearer token:

import { useKindeAuth } from '@kinde-oss/kinde-auth-nextjs'

const { getToken } = useKindeAuth()

const response = await fetch('/api/agents/support-agent/generate', {
  method: 'POST',
  headers: {
    'Authorization': `Bearer ${await getToken()}`,
    'Content-Type': 'application/json',
  },
  body: JSON.stringify({
    messages: [{ role: 'user', content: 'Hello' }],
  }),
})

For background workflows, get an M2M token via the client credentials flow:

// Server-side only — never expose client_secret in the browser
const tokenResponse = await fetch(
  `${process.env.KINDE_DOMAIN}/oauth2/token`,
  {
    method: 'POST',
    headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
    body: new URLSearchParams({
      grant_type: 'client_credentials',
      client_id: process.env.KINDE_M2M_CLIENT_ID!,
      client_secret: process.env.KINDE_M2M_CLIENT_SECRET!,
      audience: process.env.KINDE_AUDIENCE!,
    }),
  }
)

const { access_token } = await tokenResponse.json()

const agentResponse = await fetch('/api/agents/support-agent/generate', {
  method: 'POST',
  headers: {
    'Authorization': `Bearer ${access_token}`,
    'Content-Type': 'application/json',
  },
  body: JSON.stringify({
    messages: [{ role: 'user', content: 'Run the nightly summary' }],
  }),
})

Both token types work through the same provider, the same API, and the same Mastra instance.

What the provider exports

import {
  MastraAuthKinde,  // The main auth provider class
  isSystemActor,    // Returns true for M2M / client credentials tokens
} from 'mastra-auth-kinde'

Full options:

new MastraAuthKinde({
  domain: 'https://yourapp.kinde.com',     // Required
  audience: 'https://api.yourapp.com',      // Optional — only set after binding in Kinde
  allowedOrgCodes: ['org_abc123'],           // Optional — restrict to specific orgs
  name: 'kinde',                             // Optional — overrides the provider name
})

What's next

The provider is open-source and usable today at github.com/sholajegede/mastra-auth-kinde.

Kinde is free for up to 10,500 monthly active users, with no credit card required to start. You can create an account and try this provider against a test organization at kinde.com.

If this saved you time, drop a reaction. And if you're building something with Mastra agents, I'd love to hear about it in the comments.