🪢 Langfuse 图解教程Langfuse Visual Guide 第十部分 · 平台与运维Part 10 · Platform & Operations 48 / 55
第十部分 · 平台与运维Part 10 · Platform & Operations

鉴权与会话Auth & sessions

🧭 读前Before you start
先读 第20课 的 web 架构,本课讲鉴权与会话(NextAuth / JWT)。
Read Lesson 20 on the web architecture; this lesson covers auth and sessions (NextAuth / JWT).

从这一部分起,我们换上运维者的视角,看这个平台自己是怎么被「管」起来的。第一个问题最根本:谁能进来? 这一课讲鉴权(authentication,「你是谁」)与会话(session,「进来后这张身份凭证怎么发、怎么带」)。Langfuse 用 NextAuth 托管登录,给你两条进门的路:邮箱密码,或十几种 SSO(单点登录)提供商(Google、GitHub、Okta、Azure AD、Keycloak、WorkOS…)。登进来后,它发的不是一个数据库 session id,而是一张 JWT——自带签名、自带身份信息的「凭证」。 最妙的是登录成功那一刻的 session 回调:它顺手把你所属的组织/项目成员关系查出来塞进会话——这正是下一课 RBAC(你能干什么)的输入。这一课还藏着几处教科书级的安全细节,比如「用户不存在也照样算一遍密码哈希」防的是什么。

📋 生活类比
鉴权就像进一栋写字楼。门口前台要先确认「你是你」:要么你自报家门 + 出示密码(邮箱密码登录),要么你亮出一张可信第三方发的证件——比如政府身份证、公司工牌(这就是 SSO:把「证明你是谁」外包给 Google/Okta 这些可信机构,前台只认它们的背书)。 确认身份后,前台给你一张访客牌。这张牌有两种做法:一种是牌上只印个编号,你每次刷门都得让前台翻登记簿查这编号对应谁(数据库 session,每次校验都查库);另一种是牌上直接印好你的姓名、所属部门,还压了防伪钢印,门禁一扫即知、无需回前台查(这就是 JWT:自带信息 + 签名防篡改)。Langfuse 用的是后者。而且发牌那一刻,前台特意在牌背面写清你是哪几个部门/项目的成员——下一课的门禁(RBAC)就靠读这行字,决定你能推开哪些门。

两条进门的路:密码与 SSO

Langfuse 用 NextAuth(next-auth)作为鉴权框架,在 auth.ts 里注册了一长串 provider(登录方式):一个 CredentialsProvider(邮箱密码)、一个 EmailProvider(邮件魔法链接),外加十几种 SSO——Google、GitHub、GitLab、Okta、Authentik、OneLogin、Auth0、Cognito、Azure AD、Keycloak、WorkOS、WordPress。SSO 的意义是把「证明你是谁」外包给企业已经信任的身份提供商(IdP),员工不用再记一套新密码。这些 provider 分两类来源:静态(由环境变量配好)和动态(从数据库读取、运行时合并进来),后者让多租户云上的每个组织能配自己的 SSO。

谁能进来:两条路汇入 NextAuth ① 邮箱密码CredentialsProviderbcrypt 校验(本课重点) ② SSO(十几种)Google/GitHub/OktaAzure AD/Keycloak/WorkOS…外包给可信 IdP,不记新密码 NextAuth统一鉴权框架static + dynamic provider扩展 PrismaAdapter 落库 发 JWT 会话自带签名 + 身份信息下一节细讲 SSO 可被强制实例级 / 域名级 / EE 多租户禁掉密码登录、必须走 SSO
登录入口:auth.ts:24-38 导入 14 种 provider(Credentials/Email + 12 SSO),另有 CustomSSOProvider/GitHubEnterpriseProvider/JumpCloudProvider 三种服务端导入项,SSO 实际约 15 种。静态 provider 由 env 配置,动态 SSO provider 运行时从库读取并合并(auth.ts:739 附近 [...staticProviders, ...dynamicSsoProviders])。可强制 SSO:AUTH_DISABLE_USERNAME_PASSWORD(实例级)、getSSOBlockedDomains()(域名级)、getSsoAuthProviderIdForDomain(EE 多租户)。
示例:一枚会话 JWT 的解剖 eyJhbGciOiJI… . eyJzdWIiOiJ1_… . 3a7bf2c8e1… header payload signature HEADER { alg: "HS256", typ: "JWT" } PAYLOAD { sub: "u_8f3a", iat: 1719.., exp: 1719.., user: { id:"u_8f3a", email:"a@x.io", admin:false, organizations: [{ role:"ADMIN", projects:[{ role:"MEMBER" }] }] } } ↑ org 角色 + project 角色 → 第 49 课 RBAC SIGNATURE HMACSHA256( b64(header)+ "."+b64(pl), secret ) NextAuth 验签防篡改 session strategy="jwt" · maxAge = AUTH_SESSION_MAX_AGE · 改一个字节签名就失效
登录后你拿到的「身份」就是这枚签名的 JWT(形状取自 next-auth.d.ts 与 auth.ts,session.strategy="jwt";值为示例):三段 header.payload.signature。payload 里除了 sub/iat/exp,还带着整个 user——尤其是 organizations[].role 和其下 projects[].role,这正是第 49 课 RBAC 判权的依据。signature 段保证完整性:改一个字节就对不上,无法伪造越权。注意:上图是通用 JWT 结构示意;Langfuse 未注册自定义 jwt.encode/decode,故 NextAuth v4 默认签发加密的 JWE session token——payload 实际并非公开可读,完整性由 AEAD 保证。会话时效由 AUTH_SESSION_MAX_AGE 控制。
自有CredentialsProvider(邮箱密码)
最基础的一条路:用户名+密码。密码用 bcrypt 加盐哈希存库,登录时比对。下一节会看到它周围一圈安全护栏(SSO 强制、时序攻击防护、SSO 用户拦截)。
外包SSO 提供商(十几种)
把「证明身份」交给企业已信任的 IdP。员工用已有的 Google/Okta/Azure 账号一键登入,不必再设新密码——既省心又更安全(IdP 那边通常有 MFA、统一注销等企业级管控)。
落库扩展 PrismaAdapter
NextAuth 用 PrismaAdapter 把用户/账号关系存进 Postgres,Langfuse 还包了一层(extendedPrismaAdapter)定制账号绑定/字段清洗逻辑——把第三方 IdP 的用户安全地落到自己的 User 表。

密码登录的一圈安全护栏

别小看「邮箱密码」这条最朴素的路——它的 authorize 函数里藏着一圈值得细品的安全设计。先是三道 SSO 强制闸:实例级禁用密码登录(AUTH_DISABLE_USERNAME_PASSWORD)、域名级黑名单(某些公司域名必须走 SSO)、EE 多租户强制(某域名配了专属 SSO 就不许用密码)。再是一处教科书级的时序攻击防护:万一用户不存在,代码照样跑一遍密码哈希再报错——这样「用户不存在」和「密码错」两条失败路径耗时相近,攻击者就没法靠响应快慢来探测某个邮箱是否注册过。还有一处:若用户的 password 字段是 null,说明 ta 是用 SSO 注册的,明确提示「请用你绑定的 IdP 登录」。全过了才用 bcrypt 比对密码。

⚠️ 登录失败也要「长得一样、慢得一样」
若「用户不存在」直接报错、「用户存在但密码错」才慢慢算一遍 bcrypt(故意 12 轮、很慢),两条失败路径的响应时间会有可观差异——攻击者拿一堆邮箱来试,响应慢的就是已注册,不费密码就枚举出「哪些邮箱在你这注册过」(隐私泄露 + 撞库弹药)。对策:用户不存在时也白跑一遍密码哈希,让两条失败路径耗时相近。安全工程里,错误也要长得一样、慢得一样。
authorize() 的一圈安全护栏:四道全过才放行 邮箱+密码 登录尝试 ① SSO 强制三连 实例 / 域名 / EE 命中 → 拒,提示 SSO ② 查用户+时序防护 查不到也照跑 hashPassword(防枚举) ③ SSO 用户拦截 password === null → 引导用 IdP ④ bcrypt 比对 compare(pw, hash) hash 12 轮加盐 全过 → NextAuth 发会话(JWT)
1

SSO 强制三连查

实例禁密码?域名在 SSO 黑名单?该域名配了 EE 专属 SSO?——命中任一条,直接拒绝并提示走 SSO。

2

查用户 + 时序防护

按邮箱查 User。查不到也照算一遍 hashPassword 再报「Invalid credentials」——让失败耗时恒定,堵住「靠响应快慢枚举注册邮箱」的旁路。

3

SSO 用户拦截

若 dbUser.password === null,此人是 SSO 注册的、本就没密码——明确引导「请用绑定的身份提供商登录」,而非含糊报错。

4

bcrypt 比对

verifyPassword 用 bcrypt compare 比对(存储时 hash(password, 12) 12 轮加盐)。不符即「Invalid credentials」。全过才放行。

web/src/server/auth.ts · credentialsServerUtils.tsauthorize 安全护栏
async authorize(credentials) {
  // 1) SSO 强制:实例级 / 域名级 / EE 多租户
  if (env.AUTH_DISABLE_USERNAME_PASSWORD === "true") throw "… use SSO";
  if (getSSOBlockedDomains().includes(domain))         throw "… use SSO";
  if (await getSsoAuthProviderIdForDomain(domain))     throw ENTERPRISE_SSO_REQUIRED_MESSAGE;

  const dbUser = await prisma.user.findUnique({ where: { email: email.toLowerCase() } });
  if (!dbUser) {
    await hashPassword(credentials.password);  // 用户不存在也算一遍哈希 → 防时序枚举
    throw "Invalid credentials";
  }
  if (dbUser.password === null) throw "Please sign in with your identity provider…";  // SSO 用户

  const ok = await verifyPassword(credentials.password, dbUser.password);  // bcrypt compare
  if (!ok) throw "Invalid credentials";
  return userObj;   // 通过 → NextAuth 据此发会话
}

// credentialsServerUtils.ts:bcrypt 12 轮加盐
export async function hashPassword(pw) { return hash(pw, 12); }
export async function verifyPassword(pw, hashed) { return compare(pw, hashed); }

会话 = JWT + 一次「身份注入」

登录通过后,NextAuth 发的是一张 JWT(session.strategy: "jwt"),有效期 maxAge = AUTH_SESSION_MAX_AGE × 60 秒。JWT 的好处是无状态:凭证本身带着签名和身份信息,服务端验签即可,不必每次请求都查一遍 session 表——这对要水平扩展的多实例部署尤其友好。真正的点睛之笔在 session 回调:每次构建会话时,它按邮箱查出该用户的 organizationMemberships → projects 和 ProjectMemberships,把「你属于哪些组织、哪些项目、是什么角色」一并塞进 session 对象。这一步,正是把「你是谁」(本课鉴权)接到「你能干什么」(下一课 RBAC)的那根线——下一课的 throwIfNoProjectAccess 读的就是这里注入的成员关系与角色。

发 JWT + 注入成员关系 → 接到 RBAC 登录通过密码或 SSOauthorize 返回 user 发 JWT 会话strategy: "jwt"(无状态)自带签名 + 身份信息maxAge 过期即失效 session 回调(注入身份)查 organizationMemberships→ projects(未删的)+ ProjectMemberships「属于哪些组织/项目·什么角色」一并塞进 session → 第49课 RBAC据角色判 scope JWT 无状态 = 可水平扩展(验签即可,不必每请求查 session 表);session 回调把鉴权结果「翻译」成 RBAC 的输入 这个 session 回调用 instrumentAsync 包裹(第51课的 OTel 包装器)——平台连自己的登录都在自观测
JWT + 身份注入:auth.ts:743 session.strategy:"jwt"、:744 maxAge:AUTH_SESSION_MAX_AGE*60;session 回调(:747 起)查 organizationMemberships(含未删 projects,按 createdAt desc)+ ProjectMemberships 注入 session。回调体被 instrumentAsync("next-auth-session") 包裹(自观测,见第 51 课)。
会话做法数据库 session(牌上印编号)JWT(牌上印信息+钢印)← Langfuse
每次请求拿 id 回数据库查一遍本地验签即可,无需查库
水平扩展多实例需共享 session 存储天然友好:任一实例独立验签
即时吊销删库里那行即刻失效较难(需等过期或额外黑名单机制)
身份信息查库时一并取session 回调注入组织/项目成员关系
🎯 设计取舍
为什么用 JWT 无状态会话,而不是传统的数据库 session? 核心是可扩展性。数据库 session 的做法是:发一个随机 id 给浏览器,服务端把「这个 id 对应哪个用户」存进库,之后每次请求都拿 id 回库查一遍。这在单机上没问题,但 Langfuse 要跑多个 web 实例横向扩展——若用 DB session,每个实例每次请求都得访问共享的 session 存储,它就成了瓶颈和单点。JWT 把身份信息直接印在凭证里、用密钥签名防篡改,任何一个实例本地验签就能确认「你是谁」,无需回头查库——这正是无状态架构能水平扩展的关键。代价是即时吊销变难(凭证已发出去就在有效期内一直有效),所以 JWT 会配一个不太长的 maxAge,用「短有效期 + 到期重签」来折中。无状态换来了扩展性,用有效期换回了一部分可控性。

「用户不存在也照样跑一遍密码哈希」这种看似浪费的代码,到底在防什么? 防的是时序侧信道攻击(timing attack)下的用户枚举。bcrypt 故意很慢(12 轮)。如果「用户不存在」时直接报错返回、「用户存在但密码错」时才慢慢算一遍 bcrypt,那两条失败路径的响应时间会有可观差异——攻击者拿一堆邮箱来试,响应快的就是没注册、响应慢的就是已注册,于是不费密码就摸清了「哪些邮箱在你这注册过」(这本身就是隐私泄露,也是后续撞库的弹药)。对策很简单却很专业:让两条失败路径耗时相近——用户不存在时也白算一遍 hash。安全工程里,「错误也要长得一样、慢得一样」,是一条容易被忽略却很重要的原则。
🎯 本课要点
  • 鉴权 = 你是谁:NextAuth 托管,两条进门路——CredentialsProvider(邮箱密码)+ 十几种 SSO(Google/Okta/Azure AD/Keycloak/WorkOS…,把「证明身份」外包给可信 IdP)。provider 有静态(env)与动态(DB)两源。
  • 密码登录的安全护栏:SSO 强制三道闸(实例级 AUTH_DISABLE_USERNAME_PASSWORD / 域名黑名单 / EE 多租户);时序攻击防护(用户不存在也跑一遍 bcrypt 防枚举);SSO 用户拦截(password=null 引导走 IdP);最后 bcrypt(12 轮) 比对。
  • 会话 = JWT:strategy:"jwt" 无状态、自带签名与身份、maxAge 过期。相比 DB session,天然适合多实例水平扩展(本地验签免查库),代价是即时吊销较难(用短有效期折中)。
  • session 回调注入身份:构建会话时查 organizationMemberships→projects + ProjectMemberships 塞进 session——这是把「你是谁」接到下一课「你能干什么」(RBAC) 的那根线。
  • 连登录都自观测:session 回调用 instrumentAsync(第 51 课的 OTel 包装器)包裹,给登录链路也挂上 span。平台对自己的可观测,无处不在。

🧪 自测 · 想一想为什么这么设计

1. Langfuse 的密码登录里有一段「看似浪费」的代码:当用户邮箱在库里查不到时,仍然照样调用一次 hashPassword 再返回「Invalid credentials」。这段代码的目的是?
  1. 为了记录登录失败日志
  2. 为了兼容旧版密码格式
  3. 防时序攻击下的用户枚举:bcrypt故意慢,若「用户不存在」秒回而「密码错」要慢慢算,两条失败路径耗时差异会让攻击者靠响应快慢判断某邮箱是否注册过;让两路耗时相近就堵住了这个旁路
  4. 为了给数据库预热缓存
看答案与解析 点击展开
答案:C。这是安全工程里「错误也要长得一样、慢得一样」的经典实践。bcrypt 被设计成计算慢(12 轮)以抵抗暴力破解。但这个「慢」会泄露信息:如果只有「用户存在」时才走 bcrypt,攻击者拿一批邮箱来登,响应明显慢的就是已注册的——不费密码就能枚举出「谁在你这注册过」,既是隐私泄露也是撞库弹药。对策是让「用户不存在」这条路也白算一遍 hash,使两条失败路径耗时相近,时序侧信道就被堵死。许多登录实现忽略了这一点。
2. Langfuse 的会话用 JWT(session.strategy:"jwt")而不是把 session 存在数据库里。在多实例水平扩展的部署下,JWT 的核心优势是?
  1. JWT 比数据库查询更安全
  2. 无状态:身份信息直接印在凭证里并用密钥签名防篡改,任一web实例本地验签即可确认「你是谁」,无需每次请求都回头查共享session存储——后者在多实例下会成为瓶颈和单点
  3. JWT 能存更多数据
  4. JWT 永远不会过期,更省心
看答案与解析 点击展开
答案:B。数据库 session 的做法是发个随机 id、把「id→用户」存库,每次请求都拿 id 回库查。单机没问题,但 Langfuse 跑多个 web 实例横向扩展时,这个共享 session 存储就成了每请求都要访问的瓶颈和单点。JWT 把身份直接写进凭证、用密钥签名防篡改,任一实例本地验签就能确认身份,无需查库——这正是无状态架构能水平扩展的关键。代价是即时吊销变难(凭证发出后在有效期内一直有效),所以配一个不长的 maxAge 折中。这是一个典型的「用一点可控性换取扩展性」的权衡。
3. NextAuth 的 session 回调在每次构建会话时,会查出用户的 organizationMemberships→projects 和 ProjectMemberships 并塞进 session 对象。这一步在整个鉴权/授权体系里扮演什么角色?
  1. 它负责给用户的密码加密
  2. 它是把「你是谁」(鉴权)接到「你能干什么」(授权/RBAC)的那根线:把用户的组织/项目成员关系和角色注入会话,下一课的 throwIfNoProjectAccess 正是读这里注入的角色来判断 scope 权限
  3. 它决定用户能用哪些 SSO 提供商
  4. 它只是为了在页面上显示用户名
看答案与解析 点击展开
答案:B。鉴权(authentication)回答「你是谁」,授权(authorization/RBAC)回答「你能干什么」,两者需要一座桥把前者的结果交给后者。Langfuse 的这座桥就是 session 回调:登录确认身份后,它顺手把「该用户属于哪些组织、哪些项目、在每处是什么角色」查出来注入会话。于是后续任何一次权限判断(下一课的 throwIfNoProjectAccess / useHasProjectAccess)都能直接从会话里读到角色,再据角色→scope 映射判定能否执行某操作。没有这一步注入,RBAC 就拿不到判断所需的输入。
💭 发散思考(没有标准答案,动手或动脑想想)
  • 这一课展示了 Langfuse 对「邮箱密码登录」这条最朴素的路堆了一圈安全护栏:SSO 强制、时序攻击防护、SSO 用户拦截、bcrypt 加盐慢哈希。请结合你的经验谈谈:为什么「自己实现密码登录」常被认为是危险且容易出错的?这一课的哪些细节是你以前没意识到要做的?如果让你在「自建密码体系」与「全部交给 SSO/IdP」之间为一个新产品做选择,你会怎么权衡(安全、合规、用户体验、实现成本)?

From this part on, we put on the operator's hat and look at how the platform itself is "managed." The first question is the most fundamental: who gets in? This lesson covers authentication ("who are you") and the session ("once in, how is that identity credential issued and carried"). Langfuse uses NextAuth to host login, giving you two ways in: email + password, or a dozen-plus SSO (single sign-on) providers (Google, GitHub, Okta, Azure AD, Keycloak, WorkOS…). Once in, it issues not a database session id but a JWT — a "credential" carrying its own signature and identity info. The cleverest touch is the session callback at the moment of successful login: it conveniently queries your organization/project memberships and stuffs them into the session — exactly the input for the next lesson's RBAC (what you can do). This lesson also hides a few textbook security details, like what "hash the password even when the user doesn't exist" actually guards against.

📋 Analogy
Authentication is like entering an office building. The front desk must first confirm "you are you": either you state your name + show a password (email-password login), or you present a credential issued by a trusted third party — a government ID, a corporate badge (that's SSO: outsourcing "prove who you are" to trusted bodies like Google/Okta, and the front desk just trusts their endorsement). After confirming identity, the desk gives you a visitor badge. There are two ways to make this badge: one prints only a number, and every time you swipe a door the front desk must look up the registry to see whom that number maps to (database session, a DB lookup on every check); the other prints your name and department right on it, stamped with an anti-forgery seal, so the door scanner knows instantly without phoning the desk (that's JWT: self-carried info + a tamper-proof signature). Langfuse uses the latter. And at the moment of issuing the badge, the desk deliberately writes on the back which departments/projects you belong to — the next lesson's door access (RBAC) reads exactly that line to decide which doors you may push open.

Two ways in: password and SSO

Langfuse uses NextAuth (next-auth) as its auth framework, registering a long list of providers (login methods) in auth.ts: one CredentialsProvider (email-password), one EmailProvider (magic-link email), plus a dozen-plus SSO — Google, GitHub, GitLab, Okta, Authentik, OneLogin, Auth0, Cognito, Azure AD, Keycloak, WorkOS, WordPress. The point of SSO is to outsource "prove who you are" to an identity provider (IdP) the enterprise already trusts, so employees don't memorize yet another password. These providers come from two sources: static (configured by env vars) and dynamic (read from the DB and merged at runtime), the latter letting each org on multi-tenant cloud configure its own SSO.

Who gets in: two paths into NextAuth ① email + passwordCredentialsProviderbcrypt verify (this lesson's focus) ② SSO (a dozen-plus)Google/GitHub/OktaAzure AD/Keycloak/WorkOS…outsourced to trusted IdP, no new password NextAuthunified auth frameworkstatic + dynamic providersextended PrismaAdapter persists issue JWT sessionself-signed + identity infonext section details it SSO can be enforcedinstance / domain / EE multi-tenantdisable password login, force SSO
Login entry: auth.ts:24-38 imports 14 providers (Credentials/Email + 12 SSO), plus CustomSSOProvider/GitHubEnterpriseProvider/JumpCloudProvider imported server-side, so ~15 SSO in all. Static providers come from env; dynamic SSO providers are read from the DB and merged at runtime (around auth.ts:739, [...staticProviders, ...dynamicSsoProviders]). SSO can be enforced: AUTH_DISABLE_USERNAME_PASSWORD (instance), getSSOBlockedDomains() (domain), getSsoAuthProviderIdForDomain (EE multi-tenant).
Example: anatomy of a session JWT eyJhbGciOiJI… . eyJzdWIiOiJ1_… . 3a7bf2c8e1… header payload signature HEADER { alg: "HS256", typ: "JWT" } PAYLOAD { sub: "u_8f3a", iat: 1719.., exp: 1719.., user: { id:"u_8f3a", email:"a@x.io", admin:false, organizations: [{ role:"ADMIN", projects:[{ role:"MEMBER" }] }] } } ↑ org role + project role → Lesson 49 RBAC SIGNATURE HMACSHA256( b64(header)+ "."+b64(pl), secret ) verified byNextAuth session strategy="jwt" · maxAge = AUTH_SESSION_MAX_AGE · flip one byte and the signature breaks
The "identity" you get after login is this signed JWT (shape from next-auth.d.ts and auth.ts, session.strategy="jwt"; values illustrative): three parts header.payload.signature. Beyond sub/iat/exp, the payload carries the whole user — notably organizations[].role and the nested projects[].role, which is exactly what Lesson 49's RBAC checks. The signature guarantees integrity: flip one byte and it no longer matches, so privilege can't be forged. Note: the panel above shows generic JWT structure; Langfuse registers no custom jwt.encode/decode, so NextAuth v4 issues an encrypted JWE session token by default — the payload is not actually publicly readable, with integrity via AEAD. Session lifetime is controlled by AUTH_SESSION_MAX_AGE.
ownCredentialsProvider (email-password)
The most basic path: username + password. The password is stored as a bcrypt salted hash and compared on login. The next section shows a ring of security guardrails around it (SSO enforcement, timing-attack defense, SSO-user interception).
outsourceSSO providers (a dozen-plus)
Hand "prove identity" to an IdP the enterprise already trusts. Employees log in with their existing Google/Okta/Azure account in one click, no new password — easier and safer (the IdP typically has MFA, unified sign-out, and other enterprise controls).
persistextended PrismaAdapter
NextAuth uses PrismaAdapter to store user/account relations in Postgres; Langfuse wraps another layer (extendedPrismaAdapter) with custom account-linking/field-cleanup logic — safely landing third-party IdP users into its own User table.

A ring of security guardrails around password login

Don't underestimate the plainest path, "email-password" — its authorize function hides a ring of security design worth savoring. First, three SSO-enforcement gates: instance-level disabling of password login (AUTH_DISABLE_USERNAME_PASSWORD), a domain-level blocklist (certain company domains must use SSO), and EE multi-tenant enforcement (a domain configured with a dedicated SSO can't use passwords). Then a textbook timing-attack defense: if the user doesn't exist, the code still runs the password hash before erroring — so "user doesn't exist" and "wrong password" take similar time, and an attacker can't probe whether an email is registered by response speed. And one more: if the user's password field is null, they signed up via SSO, so explicitly prompt "please sign in with your linked IdP." Only after all that does it bcrypt-compare the password.

⚠️ Failed logins must "look the same and take the same time"
If "user doesn't exist" errors out instantly while "user exists but wrong password" slowly runs bcrypt (deliberately slow, 12 rounds), the two failure paths have a measurable time difference — an attacker trying a pile of emails sees slow = registered, enumerating "which emails are registered here" without ever guessing a password (a privacy leak and credential-stuffing ammo). The fix: run a throwaway password hash even when the user is absent, keeping both failure paths constant-time. This is the key timing-side-channel defense.
authorize()'s ring of guardrails: pass all four to be let in email+pw login attempt 1 SSO gates ×3 instance / domain / EE match → reject, use SSO 2 lookup + timing hash even if not found (stops enumeration) 3 SSO-user block password === null → use your IdP 4 bcrypt compare compare(pw, hash) hash, 12 salted rounds all pass → session (JWT)
1

Triple SSO-enforcement check

Instance disables passwords? Domain on the SSO blocklist? Domain configured with a dedicated EE SSO? — hit any one, reject immediately and prompt for SSO.

2

Look up user + timing defense

Find User by email. If not found, still run hashPassword before throwing "Invalid credentials" — keeping failure time constant, blocking the "enumerate registered emails by response speed" side channel.

3

Intercept SSO users

If dbUser.password === null, this person signed up via SSO and has no password — explicitly guide "please sign in with your linked identity provider," rather than a vague error.

4

bcrypt compare

verifyPassword uses bcrypt compare (stored as hash(password, 12), 12 salted rounds). A mismatch is "Invalid credentials." Only all-pass lets you in.

web/src/server/auth.ts · credentialsServerUtils.tsauthorize security guardrails
async authorize(credentials) {
  // 1) SSO enforcement: instance / domain / EE multi-tenant
  if (env.AUTH_DISABLE_USERNAME_PASSWORD === "true") throw "… use SSO";
  if (getSSOBlockedDomains().includes(domain))         throw "… use SSO";
  if (await getSsoAuthProviderIdForDomain(domain))     throw ENTERPRISE_SSO_REQUIRED_MESSAGE;

  const dbUser = await prisma.user.findUnique({ where: { email: email.toLowerCase() } });
  if (!dbUser) {
    await hashPassword(credentials.password);  // hash even if user absent → defeat timing enumeration
    throw "Invalid credentials";
  }
  if (dbUser.password === null) throw "Please sign in with your identity provider…";  // SSO user

  const ok = await verifyPassword(credentials.password, dbUser.password);  // bcrypt compare
  if (!ok) throw "Invalid credentials";
  return userObj;   // pass → NextAuth issues a session from this
}

// credentialsServerUtils.ts: bcrypt, 12 salted rounds
export async function hashPassword(pw) { return hash(pw, 12); }
export async function verifyPassword(pw, hashed) { return compare(pw, hashed); }

Session = JWT + one "identity injection"

After login passes, NextAuth issues a JWT (session.strategy: "jwt"), valid for maxAge = AUTH_SESSION_MAX_AGE × 60 seconds. JWT's benefit is being stateless: the credential itself carries a signature and identity info, the server just verifies the signature, no need to query a session table on every request — especially friendly for horizontally-scaled multi-instance deployments. The real masterstroke is the session callback: every time it builds a session, it queries that user's organizationMemberships → projects and ProjectMemberships by email, and stuffs "which orgs, which projects, what role" into the session object. This step is exactly the wire connecting "who you are" (this lesson's auth) to "what you can do" (the next lesson's RBAC) — the next lesson's throwIfNoProjectAccess reads precisely the memberships and roles injected here.

Issue JWT + inject memberships → wire to RBAC login passespassword or SSOauthorize returns user issue JWT sessionstrategy: "jwt" (stateless)self-signed + identity infomaxAge expires it session callback (inject identity)query organizationMemberships→ projects (non-deleted)+ ProjectMemberships"which orgs/projects · what role"stuffed into the session → L49 RBACjudge scope by role JWT stateless = horizontally scalable (just verify the signature, no per-request session-table lookup); the session callback "translates" the auth result into RBAC's input This session callback is wrapped in instrumentAsync (Lesson 51's OTel wrapper) — the platform self-observes even its own login
JWT + identity injection: auth.ts:743 session.strategy:"jwt", :744 maxAge:AUTH_SESSION_MAX_AGE*60; the session callback (from :747) queries organizationMemberships (with non-deleted projects, ordered createdAt desc) + ProjectMemberships into the session. The callback body is wrapped in instrumentAsync("next-auth-session") (self-observability, see Lesson 51).
Session approachDB session (badge prints a number)JWT (badge prints info + seal) ← Langfuse
Per requesttake the id, query the DB againverify the signature locally, no DB lookup
Horizontal scalingmulti-instance needs shared session storagenaturally friendly: any instance verifies independently
Instant revocationdelete that DB row to invalidate immediatelyharder (await expiry or an extra blocklist mechanism)
Identity infofetched alongside the DB lookupsession callback injects org/project memberships
🎯 Design trade-off
Why use a stateless JWT session instead of a traditional database session? The core is scalability. A DB session works by: issue a random id to the browser, store "this id maps to this user" in the DB, then on every request take the id and query the DB again. Fine on one machine, but Langfuse runs multiple web instances for horizontal scaling — with DB sessions, every instance hits the shared session store on every request, making it a bottleneck and single point. JWT prints identity info right on the credential and signs it with a key to prevent tampering, so any instance can verify locally and confirm "who you are" without a DB round-trip — the key to a stateless, horizontally-scalable architecture. The cost is that instant revocation gets harder (an issued credential stays valid through its window), so JWT pairs with a not-too-long maxAge, splitting the difference with "short validity + re-sign on expiry." Statelessness buys scalability, paid back partly with a validity window.

What does that seemingly-wasteful "hash the password even when the user doesn't exist" actually guard against? It guards against user enumeration via a timing side-channel attack. bcrypt is deliberately slow (12 rounds). If "user doesn't exist" errored out instantly while "user exists but wrong password" slowly ran bcrypt, the two failure paths would have a measurable time difference — an attacker trying a pile of emails sees fast = not registered, slow = registered, learning "which emails are registered here" without ever guessing a password (itself a privacy leak, and ammunition for later credential stuffing). The countermeasure is simple yet professional: make the two failure paths take similar time — run a throwaway hash even when the user is absent. In security engineering, "errors should look the same and take the same time" is an easily-overlooked but important principle.
🎯 Key points
  • Auth = who you are: hosted by NextAuth, two ways in — CredentialsProvider (email-password) + a dozen-plus SSO (Google/Okta/Azure AD/Keycloak/WorkOS…, outsourcing "prove identity" to a trusted IdP). Providers come from two sources: static (env) and dynamic (DB).
  • Password-login guardrails: three SSO-enforcement gates (instance-level AUTH_DISABLE_USERNAME_PASSWORD / domain blocklist / EE multi-tenant); timing-attack defense (run bcrypt even when the user is absent to block enumeration); SSO-user interception (password=null guides to the IdP); finally a bcrypt(12-round) compare.
  • Session = JWT: strategy:"jwt" stateless, self-signed with identity, maxAge expiry. Versus DB sessions, naturally suited to multi-instance horizontal scaling (verify locally, no DB lookup), at the cost of harder instant revocation (split with a short validity window).
  • Session callback injects identity: on session build it queries organizationMemberships→projects + ProjectMemberships into the session — the wire connecting "who you are" to the next lesson's "what you can do" (RBAC).
  • Even login self-observes: the session callback is wrapped in instrumentAsync (Lesson 51's OTel wrapper), attaching a span to the login path too. The platform's self-observability is everywhere.

🧪 Self-test - think about the design

1. Langfuse's password login has a 'seemingly wasteful' bit: when the email isn't found in the DB, it still calls hashPassword once before returning 'Invalid credentials'. What's the purpose?
  1. to record a login-failure log
  2. for compatibility with the legacy password format
  3. defeats user enumeration via timing attack: bcrypt is deliberately slow; if 'user absent' returns instantly while 'wrong password' runs the slow hash, the time difference lets an attacker tell whether an email is registered by response speed; making both paths take similar time closes this side channel
  4. to warm up the database cache
Show answer & explanation click to expand
Answer: C. This is the classic 'errors should look the same and take the same time' practice in security engineering. bcrypt is designed slow (12 rounds) to resist brute force. But that slowness leaks info: if only 'user exists' runs bcrypt, an attacker logging in with a batch of emails sees the noticeably-slow ones as registered—enumerating 'who's registered here' without any password, a privacy leak and credential-stuffing ammo. The countermeasure is to run a throwaway hash on the 'user absent' path too, making both failure paths take similar time and closing the timing side channel. Many login implementations miss this.
2. Langfuse's session uses JWT (session.strategy:"jwt") rather than storing sessions in a database. Under a multi-instance horizontally-scaled deployment, JWT's core advantage is?
  1. JWT is more secure than a database query
  2. stateless: identity info is printed on the credential and key-signed against tampering, so any web instance can verify locally to confirm 'who you are' without a per-request lookup to shared session storage—which under multi-instance becomes a bottleneck and single point
  3. JWT can store more data
  4. JWT never expires, more convenient
Show answer & explanation click to expand
Answer: B. A DB session issues a random id, stores 'id→user' in the DB, and queries the DB by id on every request. Fine on one machine, but when Langfuse runs multiple web instances for horizontal scaling, that shared session store becomes a per-request bottleneck and single point. JWT writes identity into the credential and signs it against tampering, so any instance verifies locally to confirm identity without a DB lookup—the key to a stateless, horizontally-scalable architecture. The cost is harder instant revocation (an issued credential stays valid through its window), so a not-too-long maxAge splits the difference. A classic 'trade a bit of control for scalability'.
3. NextAuth's session callback, on each session build, queries the user's organizationMemberships→projects and ProjectMemberships and stuffs them into the session object. What role does this step play in the whole authn/authz system?
  1. it's responsible for encrypting the user's password
  2. it's the wire connecting 'who you are' (authn) to 'what you can do' (authz/RBAC): it injects the user's org/project memberships and roles into the session, and the next lesson's throwIfNoProjectAccess reads exactly these injected roles to judge scope permissions
  3. it decides which SSO providers the user can use
  4. it's just to display the username on the page
Show answer & explanation click to expand
Answer: B. Authentication answers 'who you are', authorization/RBAC answers 'what you can do', and a bridge must hand the former's result to the latter. Langfuse's bridge is the session callback: after login confirms identity, it conveniently queries 'which orgs, which projects, what role in each' and injects them into the session. So any later permission check (next lesson's throwIfNoProjectAccess / useHasProjectAccess) reads the role straight from the session, then judges via the role→scope map whether an action is allowed. Without this injection step, RBAC wouldn't have the input it needs.
💭 Open questions (no single right answer - just think or try)
  • This lesson shows Langfuse piling a ring of guardrails on the plainest 'email-password login' path: SSO enforcement, timing-attack defense, SSO-user interception, bcrypt salted slow hashing. Drawing on your experience: why is 'rolling your own password login' often considered dangerous and error-prone? Which details here had you not realized were needed? If choosing for a new product between 'building your own password system' and 'delegating entirely to SSO/IdP', how would you weigh it (security, compliance, UX, implementation cost)?