state

Auth Session State Diagram

Model an authentication session with credential checks, token refresh loops, and the transitions that return users to anonymous.

Auth Session State Diagram — Mermaid state template preview
Static preview — open the editor for a live, editable version.

Open in editor

The code

stateDiagram-v2
  [*] --> Anonymous
  Anonymous --> Authenticating: submit credentials
  Authenticating --> Authenticated: success
  Authenticating --> Anonymous: invalid credentials
  Authenticated --> Refreshing: token expired
  Refreshing --> Authenticated: new token
  Refreshing --> Anonymous: refresh rejected
  Authenticated --> Anonymous: logout
  Anonymous --> [*]: session closed

How this template works

Authentication is where sloppy state machines cost the most, so this diagram spells the whole session out. A visitor starts Anonymous, submits credentials into an Authenticating step, and lands in Authenticated on success. When the token expires the session dips into Refreshing, which either restores Authenticated or drops the user back to Anonymous. Logout and session close are explicit transitions, not implied ones.

Read the transitions as event-driven moves. Anonymous --> Authenticating: submit credentials means the state only changes when that event fires, and the label after the colon is the event name. The loop between Authenticated and Refreshing is the part worth studying: Authenticated --> Refreshing: token expired and Refreshing --> Authenticated: new token model a cycle that users never notice when it works. The failure edge Refreshing --> Anonymous: refresh rejected is what turns a silent logout into a documented behavior. Note that the first line has no label at all — [*] --> Anonymous is legal because entering the machine is not triggered by an event.

The gotcha is symmetric loops. Because Refreshing can return to Authenticated, it is tempting to also let Authenticated re-enter Refreshing directly, and then the two states form an ambiguous pair where the trigger names are the only thing distinguishing the paths. Keep one direction of re-entry, or rename the events so each edge is unmistakable. Also resist putting spaces in state names; use MfaPending, not MFA pending.

To adapt it, add a Locked state after repeated failures with an admin-driven unlock, or insert a MfaPending state between Authenticating and Authenticated for two-factor flows. Rename states to match your identity provider’s vocabulary and the diagram becomes onboarding material for new engineers.

Related templates in the same family: the order lifecycle state diagram for e-commerce flows, the task queue state diagram for worker retries, and the subscription billing state diagram for payment states. The state diagram guide explains every construct.

Variations to try

Related templates