Principle:Langgenius Dify Authentication Flow
| Knowledge Sources | Dify |
|---|---|
| Domains | Frontend, Authentication, Security |
| Last Updated | 2026-02-12 07:00 GMT |
Overview
Dify implements a token-based authentication system with cross-tab refresh coordination for the console application and localStorage-based passport management for shared web applications.
Description
The console authentication flow centers on the refresh-token.ts module, which handles transparent access token renewal when the backend returns a 401 response. To prevent race conditions when multiple browser tabs simultaneously detect an expired token, the module uses localStorage as a cross-tab coordination mechanism. A is_other_tab_refreshing flag and a last_refresh_time timestamp ensure that only one tab performs the actual refresh request while other tabs poll and wait for completion. The refresh itself bypasses the normal baseFetch pipeline to avoid infinite retry loops and uses a dedicated fetchWithRetry utility with cookie-based credentials.
The web application authentication flow (webapp-auth.ts) manages authentication for publicly shared Dify applications. It stores access tokens and per-share-code passports in localStorage using configurable key names. Functions like webAppLoginStatus check login state against the server, while webAppLogout clears local tokens and calls the server logout endpoint. This dual-layer approach supports both enterprise SSO-redirected sessions (where tokens arrive via HTTPS cookies) and standard token-based sessions.
Both flows integrate with the service layer through the base fetch module, which automatically injects passport headers for public API requests and triggers refreshAccessTokenOrReLogin on 401 responses for console requests. The beforeunload event listener releases refresh locks to prevent stale coordination state when tabs close unexpectedly.
Usage
Use this principle when:
- Modifying token refresh behavior or adding new authentication providers
- Implementing authentication for new shared or embedded application types
- Debugging cross-tab authentication race conditions or stale token issues
Theoretical Basis
This design applies the Token Refresh with Mutual Exclusion pattern, where a distributed lock (via localStorage) prevents concurrent refresh requests across browser tabs. The separation of console authentication (cookie-based refresh tokens) from web app authentication (localStorage passports) follows the Separation of Concerns principle, recognizing that different deployment contexts require different credential storage and validation strategies.