Mockzilla logo

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.

Real-World Goal

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.

  1. Navigate to the Workflows tab.
  2. Click Create Scenario and name it auth-demo.
  3. Open the State Inspector and initialize login_attempts to 0.

Step 2: The Login Endpoint

We need an endpoint that validates credentials and "sets" a session token in our state.

POST
/login
Success Case
1

Condition

input.body.password == "password123"
2

Effects (state.set)

token{{faker.string.alphanumeric(32)}}
currentUser{{input.body.username}}

Step 3: Protecting Routes

Now, let's create a /profile endpoint that only responds if the correct token is provided in the Authorization header.

GET
Authorized
Condition

Auth == Bearer {{state.token}}

Response
200 OK
GET
Unauthorized
Condition
None (Catch-all)
Response
401 Unauthorized

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.

1
1

Add "Login Failed" Transition

Match password != "password123". Use effect state.set to set login_attempts to {{math state.login_attempts "+" 1}}.
2

Add "Account Locked" Transition

Move this to the VERY TOP of your transition list.
Match state.login_attempts >= 3 and return a
423 Locked
status code.

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

Auth Flow Mastered!

You've built a robust, stateful authentication system. Your frontend can now handle login forms, token persistence, and account lockouts with ease.