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

推荐订阅源

奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
Application and Cybersecurity Blog
Application and Cybersecurity Blog
S
Securelist
K
Kaspersky official blog
Scott Helme
Scott Helme
C
CXSECURITY Database RSS Feed - CXSecurity.com
GbyAI
GbyAI
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
C
Cisco Blogs
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
博客园 - Franky
Security Latest
Security Latest
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
Y
Y Combinator Blog
T
Threat Research - Cisco Blogs
L
LINUX DO - 热门话题
C
Cyber Attacks, Cyber Crime and Cyber Security
Project Zero
Project Zero
Cisco Talos Blog
Cisco Talos Blog
月光博客
月光博客
I
Intezer
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
人人都是产品经理
人人都是产品经理
L
Lohrmann on Cybersecurity
Recorded Future
Recorded Future
Latest news
Latest news
V2EX - 技术
V2EX - 技术
T
The Exploit Database - CXSecurity.com
H
Heimdal Security Blog
F
Fortinet All Blogs
Cloudbric
Cloudbric
IT之家
IT之家
博客园 - 叶小钗
Microsoft Security Blog
Microsoft Security Blog
P
Proofpoint News Feed
博客园 - 司徒正美
Apple Machine Learning Research
Apple Machine Learning Research
PCI Perspectives
PCI Perspectives
AWS News Blog
AWS News Blog
H
Help Net Security
S
Security @ Cisco Blogs
酷 壳 – CoolShell
酷 壳 – CoolShell
Recent Announcements
Recent Announcements
Hacker News - Newest:
Hacker News - Newest: "LLM"
cs.CV updates on arXiv.org
cs.CV updates on arXiv.org
F
Full Disclosure
S
Schneier on Security
S
Security Affairs
T
Tenable 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
Connect a user's mailbox with Nylas hosted OAuth
Qasim · 2026-06-24 · via DEV Community

Every Nylas request you make on a user's behalf needs one thing first: their permission. Before you can list a mailbox, send on someone's behalf, or read a calendar, the user has to authorize your application through their provider, and that authorization is what's called a grant. Doing the OAuth dance yourself means registering with Google and Microsoft separately, handling each provider's consent screen, token exchange, and refresh quirks. Hosted OAuth collapses that into one flow that works the same across every provider.

This post walks through connecting an account from two angles: the HTTP API your web app uses in production, and the nylas CLI for connecting a test account from the terminal. I work on the CLI, so the terminal commands below are the ones I reach for when I need a grant to develop against.

What a grant is

A grant is an authenticated connection to a single user's account. When a user authorizes your application, Nylas stores the connection and hands you a grant_id, a stable identifier you pass on every subsequent request to act on that user's email, calendar, or contacts. The grant is the unit of access: one user who connected one mailbox is one grant, and everything you build addresses /v3/grants/{grant_id}/....

Keep two credentials distinct here. Your API key authenticates your application to Nylas and goes in the Authorization header on every request; the grant_id identifies which connected user that request acts on. The API key is yours and stays on your backend, while a grant_id is minted per user when they connect. The grant is also where provider differences disappear. A Gmail grant and a Microsoft grant have different OAuth scopes and token mechanics underneath, but once connected, both are just a grant_id you use the same way. That's the point of hosted OAuth: you run one flow, the user picks their provider, and you get back the same kind of identifier regardless of who hosts the mailbox. Hosted OAuth supports Google, Microsoft, Yahoo, iCloud, IMAP, and Exchange (EWS) through this single path.

The hosted OAuth flow in three steps

Hosted OAuth is an authorization-code flow, and it has three moving parts. First, your application redirects the user to a Nylas-hosted authorization URL. Second, the user signs in to their provider and consents, and they're redirected back to your application's redirect_uri with a code (Nylas handles the hop back from the provider in between). Third, your backend exchanges that code for a grant. When the exchange succeeds, the connection is marked verified and you have a grant_id.

The division of labor matters: the first step happens in the browser, the third happens server-side where your client secret stays safe. The code is the short-lived hand-off between them, useless on its own and exchanged exactly once. If you've implemented OAuth against any provider before, this is the same pattern, with the provider-specific parts handled for you.

Build the authorization URL

The flow starts by sending the user to GET /v3/connect/auth with a few query parameters. You pass your client_id, the redirect_uri where the user is sent back after authorizing, response_type=code to request an authorization code, and a provider to skip the provider-picker when you already know it. You construct this URL and redirect the user's browser to it. It's shown expanded across lines below for readability; in practice it's a single URL with the redirect_uri percent-encoded.

https://api.us.nylas.com/v3/connect/auth?
  client_id=<NYLAS_CLIENT_ID>
  &redirect_uri=https://yourapp.com/callback
  &response_type=code
  &provider=google
  &access_type=online

The access_type parameter is worth a deliberate choice. Set it to online and Nylas doesn't generate a refresh token, which suits a session where the user is present; set it to offline when your application needs ongoing background access to the mailbox after the user leaves. After the user consents, they're redirected back to your redirect_uri with ?code=<AUTH_CODE> appended, and that code is what you exchange next.

Exchange the code for a grant

Your callback handler receives the code and exchanges it server-side with POST /v3/connect/token. The request includes your client_id, your API key as the secret, the code you received, the same redirect_uri you used to start the flow, and grant_type=authorization_code. This call must run on your backend, never in the browser, because it carries your credentials.

curl --request POST \
  --url "https://api.us.nylas.com/v3/connect/token" \
  --header "Content-Type: application/json" \
  --data '{
    "client_id": "<NYLAS_CLIENT_ID>",
    "client_secret": "<NYLAS_API_KEY>",
    "code": "<AUTH_CODE>",
    "redirect_uri": "https://yourapp.com/callback",
    "grant_type": "authorization_code"
  }'

The response contains the grant_id, which you store against your user record. From this point the user is connected, and every Messages, Calendar, or Contacts call you make uses that grant_id. The code is now spent; a second exchange of the same code fails, which is the flow working as intended.

Connect a test account from the CLI

In production the flow above runs across your frontend and backend, but for development you don't want to stand all that up just to get a grant to test against. The CLI runs the entire OAuth flow from the terminal: nylas auth login opens the provider's consent screen in your browser, you sign in, and the CLI stores the resulting grant as your active account.

# Connect a Google account (the default)
nylas auth login

# Connect a different provider
nylas auth login --provider microsoft
nylas auth login --provider imap

The --provider flag picks the mailbox type, with google, microsoft, ews, icloud, yahoo, and imap available. Once connected, the grant becomes the default that every other nylas command uses, so nylas email list or nylas calendar find-time runs against it immediately. It's the fastest way to get a real, authorized mailbox to build against without writing a callback handler first.

Skip the provider picker

If you collect the user's email before sending them into the flow, you can skip the provider-selection screen. Passing provider=google (or microsoft, and so on) on the auth URL sends the user straight to that provider's consent screen instead of a chooser. When you don't know the provider, nylas auth detect infers it from the email address, and nylas auth providers lists the ones available.

nylas auth detect user@example.com

Detecting the provider up front makes the connection feel like one step to the user rather than two, and it avoids the mismatch of someone picking the wrong provider for their address. In a web app, you'd run the equivalent detection server-side and set the provider parameter before you build the authorization URL.

List and inspect your grants

Once accounts are connected, you manage them through the Grants API. GET /v3/grants lists every grant on your application, and GET /v3/grants/{grant_id} returns one, including its provider, email, and grant_status. This is how your application checks whether a user's connection is still healthy before it relies on it.

curl --request GET \
  --url "https://api.us.nylas.com/v3/grants" \
  --header "Authorization: Bearer <NYLAS_API_KEY>"

From the terminal, nylas auth list shows every connected account, nylas auth show prints the details of one, and nylas auth scopes displays the OAuth scopes a grant was granted. Checking scopes is useful when a call fails with a permission error, since it tells you whether the user actually authorized the access your code is trying to use.

Revoke a grant

When a user disconnects, or you're cleaning up, you revoke the grant. DELETE /v3/grants/{grant_id} removes the connection on the Nylas side, after which the grant_id no longer works and you stop being able to access that mailbox. Deleting a grant is the clean way to honor a user's disconnect request, since it severs the stored authorization entirely.

curl --request DELETE \
  --url "https://api.us.nylas.com/v3/grants/<GRANT_ID>" \
  --header "Authorization: Bearer <NYLAS_API_KEY>"

The CLI equivalent is nylas auth revoke, which revokes a grant from the server, and nylas auth logout for the active one. There's a distinction worth knowing: nylas auth remove drops a grant from your local CLI config without revoking it on the server, while revoke actually severs the connection. Use revoke when you mean to disconnect the account, not just forget it locally.

When a grant goes stale

A grant isn't permanent. A user can revoke access at their provider, change their password, or hit a provider policy that invalidates the connection, and when that happens the grant's grant_status reflects it rather than the grant_id silently failing. The grant object carries a grant_status field, valid or invalid, so a quick fetch tells you whether a connection is still healthy, and Nylas emits a grant.expired webhook so your application learns about a broken connection without polling for it.

The fix for a stale grant is to reconnect, not to delete and recreate. You send the user back through the same hosted OAuth flow, and the refreshed authorization restores access for that account. Wiring up the grant webhooks means you can prompt exactly the users who need to re-authenticate, instead of discovering broken connections one failed request at a time. That's the difference between a user noticing their integration broke and your application catching it first.

Online versus offline access

The access_type choice from the auth URL has consequences worth understanding. With access_type=online, no refresh token is generated, so the grant is suited to flows where the user is actively present and you don't need to touch the mailbox once they leave. It's the lighter-weight option when you're acting in direct response to a user.

For most production integrations you want ongoing access, an agent that processes mail overnight or a sync that runs on a schedule. There you set access_type=offline so the grant gets a refresh token and can maintain access without the user being present. Nylas handles the token refresh underneath, so you don't manage refresh tokens yourself; the grant stays valid and your grant_id keeps working. Choosing the wrong mode shows up later: an online grant can't be refreshed for background use and stops working once its access token expires unless the user re-authenticates, so set it intentionally up front.

Things to keep in mind

A few practices keep an authentication integration solid from the first grant onward.

  • Exchange the code server-side. The token exchange carries your credentials, so it belongs on your backend, never in browser-side code.
  • Store the grant_id, not the code. The code is single-use and short-lived; the grant_id is the durable handle you keep against your user.
  • Pick access_type deliberately. Use online for present-user flows and offline for background access; the wrong choice surfaces as a grant that expires unexpectedly.
  • Check scopes when a call is forbidden. nylas auth scopes or the grant object tells you what the user actually authorized.
  • Revoke, don't just forget. Deleting a grant or nylas auth revoke severs access; removing it locally only hides it from your config.
  • Detect the provider to skip a step. Pass provider on the auth URL, or use nylas auth detect, so the user skips the chooser and lands on the right consent screen.

Wrapping up

Connecting a mailbox is one flow with three steps: redirect to the authorization URL, receive a code at your callback, and exchange it for a grant_id. From there the provider differences vanish, and every Email, Calendar, and Contacts call uses the same identifier. For development, nylas auth login runs the whole flow from the terminal so you have a real grant in seconds, and the Grants API plus nylas auth commands let you list, inspect, and revoke connections as users come and go.

Where to go next: