Tutorial: Building a Stateful Auth Flow
In this tutorial, you will build a realistic authentication simulation. Unlike static mocks, Mockzilla Workflows can remember if a user has logged in, allowing you to test protected routes and session expiration logic in your frontend.
Simulate a login system where a user provides credentials, receives a random token, and uses that token to access their profile. We'll even add an "Account Lockout" feature for too many failed attempts!
Step 1: Initialize the Scenario
First, we need a sandbox for our authentication logic.
- Navigate to the Workflows tab.
- Click Create Scenario and name it
auth-demo. - Open the State Inspector and initialize
login_attemptsto0.
Step 2: The Login Endpoint
We need an endpoint that validates credentials and "sets" a session token in our state.
/loginCondition
Effects (state.set)
token → {{faker.string.alphanumeric(32)}}currentUser → {{input.body.username}}Using {{faker}} inside a state.set effect ensures that the token is generated once during login and remains persistent until the next login.
Step 3: Protecting Routes
Now, let's create a /profile endpoint that only responds if the correct token is provided in the Authorization header.
Auth == Bearer {{state.token}}
Step 4: Account Lockout (Advanced Logic)
Let's use Arithmetic to increment a counter and Conditions to branch logic when a user fails to login.
Add "Login Failed" Transition
password != "password123". Use effect state.set to set login_attempts to {{math state.login_attempts "+" 1}}.Add "Account Locked" Transition
state.login_attempts >= 3 and return a Step 5: Verify the Journey
Open your terminal and simulate the full user journey:
1. Attempt Unauthorized Access
curl -i http://localhost:36666/api/workflow/exec/auth-demo/profile
2. Login to generate a session
curl -X POST http://localhost:36666/api/workflow/exec/auth-demo/login \
-d '{"username": "Alice", "password": "password123"}'
3. Access profile with your token
curl -H "Authorization: Bearer YOUR_TOKEN" \
http://localhost:36666/api/workflow/exec/auth-demo/profile
