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.
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).
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.
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.
asyncauthorize(credentials) {
// 1) SSO enforcement: instance / domain / EE multi-tenantif (env.AUTH_DISABLE_USERNAME_PASSWORD === "true") throw"… use SSO";
if (getSSOBlockedDomains().includes(domain)) throw"… use SSO";
if (awaitgetSsoAuthProviderIdForDomain(domain)) throw ENTERPRISE_SSO_REQUIRED_MESSAGE;
const dbUser = await prisma.user.findUnique({ where: { email: email.toLowerCase() } });
if (!dbUser) {
awaithashPassword(credentials.password); // hash even if user absent → defeat timing enumerationthrow"Invalid credentials";
}
if (dbUser.password === null) throw"Please sign in with your identity provider…"; // SSO userconst ok = awaitverifyPassword(credentials.password, dbUser.password); // bcrypt compareif (!ok) throw"Invalid credentials";
return userObj; // pass → NextAuth issues a session from this
}
// credentialsServerUtils.ts: bcrypt, 12 salted roundsexport async functionhashPassword(pw) { returnhash(pw, 12); }
export async functionverifyPassword(pw, hashed) { returncompare(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.
JWT + identity injection: auth.ts:743session.strategy:"jwt", :744maxAge: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 approach
DB session (badge prints a number)
JWT (badge prints info + seal) ← Langfuse
Per request
take the id, query the DB again
verify the signature locally, no DB lookup
Horizontal scaling
multi-instance needs shared session storage
naturally friendly: any instance verifies independently
Instant revocation
delete that DB row to invalidate immediately
harder (await expiry or an extra blocklist mechanism)
Identity info
fetched alongside the DB lookup
session 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?
to record a login-failure log
for compatibility with the legacy password format
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
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?
JWT is more secure than a database query
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
JWT can store more data
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?
it's responsible for encrypting the user's password
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
it decides which SSO providers the user can use
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)?