zrizDocsLearnSecuritySign inSign up

Test that an API returns 401 without a token

Call a protected endpoint with no token and with a bad token in one zriz pipeline. Each call must get status 401 and no data.

Lesson 3 of 10 · zz 0.8.0 or later · Updated · Plain text for agents: /learn/test-api-401-without-token.md

The problem

A protected endpoint must refuse a call that has no valid token. One wrong line in a route file can open it to all. No error shows this: the endpoint works, also for a stranger.

The test

The example is a shop API. GET /api/auth/me gives the data of the user that the token names.

Start from a project that zz init made: the quick start gives the commands. Add the action me to the resource file.

.zriz/resources/target.json:

{
  "type": "http",
  "description": "Your app under test",
  "base-url": "${env.TARGET_URL}",
  "headers": { "Content-Type": "application/json" },
  "actions": {
    "check": { "method": "GET", "path": "/api/health" },
    "me": { "method": "GET", "path": "/api/auth/me" }
  }
}

.zriz/pipelines/me-needs-token.json:

{
  "description": "No token and a bad token: the API must answer 401",
  "steps": [
    {
      "call": "target/me",
      "expect": [
        ["status", "==", 401],
        ["body.error", "==", "missing or invalid authorization header"],
        ["body.email", "not-exists"]
      ]
    },
    {
      "call": "target/me",
      "headers": { "Authorization": "Bearer not-a-real-token" },
      "expect": [
        ["status", "==", 401],
        ["body.error", "==", "invalid token"],
        ["body.email", "not-exists"]
      ]
    }
  ]
}

Run it

zz run me-needs-token
"status":"pass"

What it proves

Note: Add one such pipeline for each protected endpoint. The test is short, and a new endpoint is where the fault comes in.

Next