QA Interview Hub · Knowledge base · Quizzes · Українська

API

Authentication and authorization

JWT and testing tokens

A JWT is a signed string header.payload.signature, where the first two parts are JSON in Base64URL and the signature guarantees the token was not altered. The payload is only encoded, not encrypted, so secrets do not belong there. The server must check the signature, exp and allowed algorithms itself instead of trusting the token's header (the alg: none attack). Expired and forged tokens must yield 401 with WWW-Authenticate.

API · Authorization

The token expired long ago, yet the API answers 200. What does the server actually check?

A tester takes a token from yesterday's run, sends a request to /v1/me and gets 200 with a profile. The token was supposed to live 15 minutes. The developer says: "The signature is valid." True, a signature does not change with time, while checking the exp field is a separate step that is easy to forget. To test tokens you need to know what they consist of and which part the server must check itself.

Below: how a JWT is built, what in it is trusted and what is not, and a set of negative cases that catches the typical defects.

How a JWT is built

A signed JSON Web Token (JWT, RFC 7519; signature per JWS, RFC 7515) is a string of three parts joined by dots: header.payload.signature. Each of the first two parts is JSON in Base64URL encoding, the third is a signature over the first two. An encrypted variant (JWE) exists but is rare.

// header
{ "alg": "HS256", "typ": "JWT" }

// payload (claims)
{ "sub": "42", "role": "user", "iat": 1764496400, "exp": 1764497300 }

// signature = HMAC-SHA256(base64url(header) + "." + base64url(payload), secret)

Three parts of a JWT

1 header: alg, typ 2 payload: sub, role, exp 3 signature: over 1 and 2
Figure 1. The first two parts are signed. Changing any byte in them breaks the signature, but anyone can read them.

Why it is designed this way. A JWT lets the server skip the database on each request: everything needed (who this is, the role, until when the token is valid) is inside the token, and the signature guarantees nobody changed it. Two consequences follow, and they define the tests. First, Base64URL is an encoding, not encryption: passwords and sensitive data do not belong in the payload, because anyone holding the token can read them. Second, trust rests on the signature, so the server must verify it itself, check exp itself, and keep a list of allowed algorithms (in the library configuration, not taken from the token header).

The main claims from RFC 7519: exp (when the token stops being valid, seconds since 1970), iat (when issued), nbf (not before), sub (who), iss (who issued it), aud (for whom). A role or permissions are usually extra, custom claims. The token travels in the header Authorization: Bearer <token>.

Access and refresh tokens

Access token

Lives minutes. Goes with every API request. If stolen, the damage is limited by time.

Refresh token

Lives days or weeks. Goes only to the token endpoint. It is revoked and rotated on the server.

Figure 2. A pair of tokens: a short one for everyday calls, a long one only for getting a new short one.

Example: an expired token and an alg none token

We suspect the server looks only at the signature. We check with what it must reject. A token with "alg": "none" (no signature) and admin rights must get 401. Here is a response that is a serious defect (the token is shortened to its structure, the full string looks the same):

GET /v1/me HTTP/1.1
Authorization: Bearer eyJhbGciOiJub25lIiwidHlwIjoiSldUIn0.eyJzdWIiOiI0MiIsInJvbGUiOiJhZG1pbiJ9.

HTTP/1.1 200 OK
Content-Type: application/json

{ "id": "42", "role": "admin" }

The server believed the token header, which is controlled by the client, and accepted an "unsigned" token. This is a well-known library vulnerability, closed by an explicit list of allowed algorithms. A set of negative cases catches it together with an expired and a forged token. The test helper builds tokens itself, because broken ones are exactly what we need:

import { createHmac } from 'node:crypto';
import { test, expect } from '@playwright/test';

const b64 = (o: object) => Buffer.from(JSON.stringify(o)).toString('base64url');

function forge(payload: object, alg = 'HS256') {
  const head = b64({ alg, typ: 'JWT' });
  const body = b64(payload);
  if (alg === 'none') return head + '.' + body + '.';
  const sig = createHmac('sha256', 'wrong-secret')
    .update(head + '.' + body).digest('base64url');
  return head + '.' + body + '.' + sig;
}

const now = Math.floor(Date.now() / 1000);
const admin = { sub: '42', role: 'admin', exp: now + 600 };
const cases = [
  { name: 'expired', token: forge({ sub: '42', exp: now - 60 }) },
  { name: 'wrong signature', token: forge(admin) },
  { name: 'alg none', token: forge(admin, 'none') },
  { name: 'truncated', token: 'eyJhbGciOiJIUzI1NiJ9.eyJzdWIi' },
];

for (const c of cases) {
  test('GET /v1/me with a ' + c.name + ' token', async ({ request }) => {
    const res = await request.get('/v1/me', {
      headers: { Authorization: 'Bearer ' + c.token },
    });
    expect(res.status()).toBe(401);
    expect(res.headers()['www-authenticate']).toMatch(/^Bearer/);
  });
}

Every case expects 401 and a WWW-Authenticate: Bearer header, which HTTP requires in a 401 response. The signature in the "wrong signature" case is made with a foreign secret: this is the same as changing the role in the payload without re-signing, because the signature no longer matches the content. Three more cases need no helper: an empty header, a scheme other than Bearer, and a token from another environment (staging on prod).

Limits and alternatives

  • A stateless JWT means issuing is easy and revoking is hard: after logout or a password change it formally works until exp. A service either keeps a list of revoked tokens, or has a very short exp and revokes the refresh token. The policy comes from the contract, and the test checks exactly it.
  • Server clocks can drift, so many services allow a small leeway on exp and nbf. Test the time boundary with a margin (a token that expired an hour ago), not by one second.
  • Opaque tokens are checked by the server with a store lookup or an introspection endpoint. They are easy to revoke but add a call. This is an alternative to JWT, not a mistake.
  • Symmetric (HS256) tokens need a shared secret, asymmetric (RS256, ES256) ones can be verified with a public key. For a client that only reads the payload, there is no difference.

Common mistakes

  • Checking only "a valid token gives 200". Negative cases (exp, signature, algorithm) are where most token-validation defects are found.
  • Taking an expired token from yesterday's run. The test depends on time and becomes unstable. The token is built in the test or a fresh one is obtained by login.
  • Treating the payload as secret. Anyone can decode it (for example on jwt.io), so a password or a card number there is a defect.
  • Mixing up 401 and 403. A missing or broken token is 401, a valid token without rights is 403.

Check yourself

A test changes the role in the payload from user to admin but keeps the old signature. The server returns 200 and admin data. What is the defect?

Answer

The server does not verify the signature (or trusts the payload before verifying). The signature is computed over the header and the payload, so any change to the payload must break it, and the response must be 401.

After logout the same access token still gives 200 for 5 minutes. Is that a bug?

Answer

It depends on the contract. For a JWT without a revocation list it is expected until exp. It is a bug if the documentation promises immediate invalidation, or if the refresh token still works after logout. Both are checked.

In an interview. Junior: A JWT has three parts: a header, a payload and a signature, encoded in Base64URL. The payload is not encrypted, anyone can read it, and the signature shows the token was not changed. I check 401 for an expired, forged and truncated token. Middle/Senior: The server must verify the signature, exp, iss/aud and the allowed algorithms itself, not trust the token header (the alg none attack). I generate broken tokens with a helper and check 401 together with WWW-Authenticate. Separately I find out the revocation policy: after logout or a password change a stateless token lives until exp.

Authorisation types in Postman

Postman supports Bearer Token, Basic, API Key, OAuth 2.0 and other types, with authorisation set on the collection, folder or request and inherited. Login and public endpoints get No Auth. Basic is only Base64 encoding, so it is checked over HTTPS, and an API key is better sent in a header because a query string ends up in logs. A collection is not exported with secret values.

API · Authorization

A collection has 80 requests and the token changed. How many places need fixing?

A Postman collection has 80 requests. Someone pasted a Bearer token into each one, now it has expired, and every request returns 401. Nobody wants to fix 80 tabs by hand, and if even one is missed, it will quietly fail a few days later. Authorization types are not just a list in a drop-down: the question is where it is set and what exactly ends up in the request.

Below: what each type does, how inheritance removes duplication, and where each type has a risk.

Authorization types and how they look in a request

TypeWhat goes in the requestRisk
Bearer TokenAuthorization: Bearer <token>The token works until it expires; theft gives access
Basic AuthAuthorization: Basic base64(login:password)It is encoding, not encryption
API KeyA header (x-api-key) or a queryIn a query it lands in logs and history
OAuth 2.0Postman runs the flow and inserts the access tokenHarder to set up, but the token is short-lived
Cookie sessionNot a separate type in the Authorization tab: Postman stores the session cookie after login and sends it itselfNeeds CSRF protection, and a cookie is not added to another domain automatically

The same from the command line, to see what exactly goes into the request without Postman:

# Bearer
curl -i "$BASE/v1/me" -H "Authorization: Bearer $TOKEN"

# Basic: curl builds base64("login:password") itself
curl -i -u "test:password" "$BASE/v1/me"
# the same by hand: Authorization: Basic dGVzdDpwYXNzd29yZA==

# API key in a header, and in the query (the second one lands in logs)
curl -i "$BASE/v1/me" -H "x-api-key: $KEY"
curl -i "$BASE/v1/me?api_key=$KEY"

# Cookie session: the cookie is set by login, then sent back
curl -i -c jar.txt -X POST "$BASE/auth/login" -d '{"login":"test"}' \
  -H "Content-Type: application/json"
curl -i -b jar.txt "$BASE/v1/me"

How inheritance works and why it is needed

Auth can be set at three levels: collection, folder, request. The request mode Inherit auth from parent takes the setting of the nearest parent that sets it. Login and public endpoints get No Auth, so they can be tested without a token.

Where a request gets its authorization

1 collection: Bearer {{token}} 2 folder: Inherit 3 request: Inherit auth from parent 4 login: No Auth
Figure 1. The setting lives in one place and requests inherit it. An exception (login) is set explicitly.

Why it is designed this way. Auth repeated in 80 places inevitably drifts: one request has an old token, another a foreign one, a third none at all. A central place is changed once, and a test with No Auth is then a conscious exception, not an accident. One more benefit: to check "without a token", you switch the mode on one request without touching the collection.

Example: where exactly the risk hides

The Basic test for an internal service passes. The real request looks like this:

GET /v1/me HTTP/1.1
Authorization: Basic dGVzdDpwYXNzd29yZA==

# decode in a shell: echo dGVzdDpwYXNzd29yZA== | base64 -d
# result: test:password

The login and password are recovered in a second, so over HTTP without TLS they go practically in plain text. First test: the service opens only over HTTPS, and on http:// it either rejects the request or redirects (301/308) and in no case processes the credentials. Second test: a wrong password gives 401 with WWW-Authenticate: Basic. For an API Key it is similar: a key in a header is the norm, a key in the query is a design remark, because the URL is written to server and proxy logs and stays in the browser history.

Token or cookie session

Bearer token

The client adds the header itself. Independent of a browser, handy for mobile and service-to-service. Needs no CSRF protection.

Cookie session

The browser adds the cookie itself. Handy for the web, but needs HttpOnly, Secure, SameSite and CSRF protection.

Figure 2. Both approaches are legitimate and the choice depends on the client. The test checks the one described in the contract.

Limits and alternatives

  • Postman also has Digest, Hawk, AWS Signature, NTLM and other types. They are rarely asked about in interviews, and at work they appear in specific integrations.
  • Values of variables with secrets are kept in the environment, not in a collection that is exported to a repository. For sharing, use the built-in vault or CI variables.
  • In Playwright or curl the same types are set by a header or an option (-u, extraHTTPHeaders). The principle does not depend on the tool.
  • Postman Inherit is only a way to pass the token. Whether the server handles it correctly must be checked with separate cases.

Common mistakes

  • Pasting the token into every request. A week later some requests fail with 401 and the cause takes long to find.
  • Leaving Inherit on login. It sends an old token to an endpoint that does not expect one, and the result is confusing.
  • Considering Basic safe. Base64 decodes in a second, and without HTTPS it is plain text.
  • Exporting a collection with a real token. The secret ends up in the repository. Export variables without values.

Check yourself

A request in Inherit mode returns 401 although the collection has a token. What to check first?

Answer

Whether the collection or a folder in between really sets auth, and whether the {{token}} variable has a value in the active environment. An empty variable gives a Bearer header with no token. The Postman console shows what exactly went into the request.

Why is an API Key in a query parameter worse than in a header?

Answer

The URL is written to server and proxy logs, stays in the browser history and can leak through Referer. Headers are not logged that way by default, so the key is safer there.

In an interview. Junior: Most often a Bearer token, usually a JWT. I set authorization on the collection, requests inherit it, and login gets No Auth. I also know Basic, API Key, OAuth 2.0 and cookie sessions. Middle/Senior: Basic is encoding, so I test it only over HTTPS, and I treat an API Key in the query as a design remark because of logs. I tell a header token from a cookie session: the second needs CSRF protection. I do not export a collection with secret values.

The token automatically and what to check

A login post-response script saves the token to a variable used as Bearer {{token}}, and a pre-request script refreshes it before expiry. Mandatory checks: no token, a broken and an expired token give 401, someone else's resource gives 403 or 404, and an ordinary user on an admin endpoint gives 403. For BOLA/IDOR two users are used, checking both the status and the absence of the owner's data in the body.

API · Authorization

The token lives 15 minutes, the collection runs an hour. How to avoid pasting it by hand?

A regression run of 60 requests. The first 20 pass, then 401s begin: the token pasted in the morning expired halfway. Refreshing the token by hand before every run is a source of unstable runs and lost time. The token must be obtained automatically, and along with it we check that authorization behaves correctly when there is no token, when it is broken or when it belongs to someone else.

Below: how to save the token after login, how to refresh it when it expires, and which set of checks is mandatory.

How the token gets into requests automatically

Postman runs scripts before and after a request. In the post-response script of the login the token is saved to an environment variable, and the collection is set to Bearer {{token}}.

// Tests tab of POST {{baseUrl}}/auth/login (post-response script)
pm.test('login: 200', () => pm.response.to.have.status(200));

const { accessToken, expiresIn } = pm.response.json();
pm.expect(accessToken, 'accessToken').to.be.a('string');

pm.environment.set('token', accessToken);
pm.environment.set('tokenExpiresAt', Date.now() + expiresIn * 1000);

The chain from login to requests

1 POST /auth/login 2 test: status 200, token present 3 pm.environment.set(token) 4 collection: Bearer {{token}} 5 requests use the fresh token
Figure 1. The token passes from one request to all of them through an environment variable, not by manual copying.

Why it is designed this way. An environment variable is shared state between the requests of a collection: the write script runs once, and the {{token}} substitution happens on every send. The token lives in a variable, not in a request, so it changes in one place. The order matters here: in Runner and Newman login must be the first request, because the following ones read the variable it writes.

Example: a token that expires in the middle of a run

Before: login once at the start, but the collection runs longer than the token lives, so the middle fails with 401. After: before each request we check the expiry time and, if needed, get a new token. This is the collection pre-request script:

// Collection > Pre-request Script: refresh the token when it is near expiry
const expiresAt = Number(pm.environment.get('tokenExpiresAt') || 0);

if (Date.now() > expiresAt - 30000) {
  pm.sendRequest(
    {
      url: pm.environment.get('baseUrl') + '/auth/login',
      method: 'POST',
      header: { 'Content-Type': 'application/json' },
      body: {
        mode: 'raw',
        raw: JSON.stringify({
          login: pm.environment.get('login'),
          password: pm.environment.get('password'),
        }),
      },
    },
    (err, res) => {
      if (err) throw err;
      const { accessToken, expiresIn } = res.json();
      pm.environment.set('token', accessToken);
      pm.environment.set('tokenExpiresAt', Date.now() + expiresIn * 1000);
    },
  );
}

The 30-second margin is needed so the token does not expire while the request is in flight. The login and the password come from environment variables, not from the script text. A script like this sends the extra request only when the token is really old, so the collection does not get slower without need. Note that pm.sendRequest is asynchronous, and the main request waits for the script to finish.

What to check in authorization

  • No token: 401, not 200 and not 500.
  • A broken and an expired token: 401, with no details about the reason in the body.
  • A token after logout: 401 if the contract promises invalidation; otherwise the policy is recorded.
  • Someone else's resource: user B's token on a resource of A gives 403 or 404, but never data.
  • Role rights: an ordinary user on an admin endpoint gives 403.

The last two points are BOLA/IDOR, one of the most dangerous defects in fintech. Two test users are needed: create a resource as the first and request it with the token of the second. The same in code, with tokens obtained once per worker:

import { test as base, expect, request as pw } from '@playwright/test';

async function login(user: string) {
  const ctx = await pw.newContext({ baseURL: process.env.API_URL });
  const res = await ctx.post('/auth/login', {
    data: { login: user, password: process.env.TEST_PASSWORD },
  });
  const { accessToken } = await res.json();
  await ctx.dispose();
  return accessToken as string;
}

const test = base.extend<{}, { tokenA: string; tokenB: string }>({
  tokenA: [async ({}, use) => use(await login('user-a')), { scope: 'worker' }],
  tokenB: [async ({}, use) => use(await login('user-b')), { scope: 'worker' }],
});

test('user B cannot read the transfer of user A', async ({ request, tokenA, tokenB }) => {
  const created = await request.post('/v1/transfers', {
    headers: { Authorization: 'Bearer ' + tokenA },
    data: { toAccount: 'UA21...', amount: 10, currency: 'UAH' },
  });
  const { id } = await created.json();

  const res = await request.get('/v1/transfers/' + id, {
    headers: { Authorization: 'Bearer ' + tokenB },
  });
  expect([403, 404]).toContain(res.status());
  expect(await res.text()).not.toContain('UA21');
});

The test checks two assumptions: the status is not 200, and there is no owner data in the body (a check by a fragment of the account number). The status alone is not enough: a server can return 403 with the full object in the body.

Limits and alternatives

  • A script that logs in before every request without checking the expiry overloads the login service and can hit a rate limit. Refresh only when needed.
  • For OAuth 2.0 Postman can obtain and refresh the token itself (Get New Access Token, auto-refresh). For a simple login on your own endpoint, scripts are handier.
  • In Newman environment variables are not kept between runs, so the token is obtained within a run.
  • In Playwright the analogue is a worker-scoped fixture or a setup project that logs in once and shares the state. The approach is the same: the token in one place, tests do not know about it.

Common mistakes

  • Not checking the login status in the script. If login failed, undefined is written to the variable and the next 59 requests give 401 with no clear reason.
  • One test user for everything. Checking someone else's access is impossible, and IDOR goes unnoticed.
  • Checking only the status of foreign access. A 403 with data in the body is the same leak.
  • Login and password in the script text or the collection. They end up in the repository and in logs. They are kept in environment variables or CI secrets.

Check yourself

A collection run fails with 401 at request 21 while everything was fine at the start. What is the likeliest cause and the fix?

Answer

The token expired in the middle of the run: it was obtained once, and the collection is longer than its lifetime. Add a pre-request script that refreshes the token when less than a margin is left, or run the collection in shorter parts.

A GET of someone else's account with another user's token returns 403, but the body contains the full account JSON. Did the test pass?

Answer

No. The status is right, but the data leaked, so this is BOLA/IDOR with a wrong status. Both the code and the absence of owner data in the body are checked.

In an interview. Junior: After login I save the token with pm.environment.set and use {{token}} on the collection. I check 401 with no token, with a broken one, an expired one and after logout. Middle/Senior: I refresh the token in a pre-request script when less than a margin is left, not before every request. For IDOR I take two users: I create a resource as the first and read it with the token of the second, checking both the status and the absence of data in the body. I keep the login and password in environment variables, not in the collection.

OAuth 2.0 and OpenID Connect: roles, flows and what to test

OAuth 2.0 is a protocol of delegated access: an app gets limited access to a user's resources without their password. OpenID Connect adds authentication, the answer to who this is. Web and mobile use Authorization Code with PKCE, service-to-service uses Client Credentials. Tests cover single-use codes, the verifier, an exact redirect URI and state; a valid token lacking the scope gets 403, an invalid one 401.

API · Authorization

"Sign in with Google" in an app. Who gives what to whom, and what is there to test?

An app has a "Sign in with Google" button. The user types the password on the Google page, the app never sees it and receives only a token. A tester gets the task "check authorization" and does not know where to start: whom to look at, how the tokens differ, why one error is returned as 401 and another as 403. The answer is in the roles and flows of OAuth 2.0.

Below: the roles, the Authorization Code flow with PKCE, what the access, refresh and ID tokens are, and a set of cases with example requests.

What it is and why

OAuth 2.0 (RFC 6749) is a protocol of delegated access: an app gets limited access to a user's resources without the user's password. OpenID Connect (OIDC) is a layer on top of OAuth 2.0 for authentication: it answers "who is this user". There are four roles: the resource owner (the user), the client (the app), the authorization server (issues tokens) and the resource server (the API that accepts tokens).

How Authorization Code with PKCE works

This is the standard flow for web, mobile and SPA. The user signs in at the authorization server, the client gets a one-time code and exchanges it for tokens. To make a stolen code useless, the client adds PKCE (RFC 7636): a random code_verifier from which a code_challenge is computed.

The Authorization Code flow with PKCE

1 client: verifier and challenge 2 browser: /authorize + state 3 user signs in and consents 4 redirect: ?code=...&state=... 5 client checks state 6 POST /token: code + verifier 7 access + refresh (+ ID token)
Figure 1. The code travels through the browser, while tokens are obtained by a direct request from the client to the authorization server. The verifier stays with the client, so an intercepted code is useless without it.

Why it is designed this way. The code goes through the address bar and the browser, a place where it can be intercepted (redirects, logs, a malicious app on a phone). So the code is one-time and short-lived, and tokens are issued only for a direct request where the client proves it started the sign-in: it sends the verifier whose hash was in the first request. The state parameter binds the response to the original request and protects against CSRF. An exact match of the redirect URI with the registered one prevents sending the code to a foreign address. This binding is exactly what the tests check.

The code-for-tokens exchange looks like this:

POST /oauth/token HTTP/1.1
Host: auth.shop.test
Content-Type: application/x-www-form-urlencoded

grant_type=authorization_code&code=SplxlOBeZQQYbYS6WxSbIA
&redirect_uri=https%3A%2F%2Fapp.shop.test%2Fcb&client_id=web
&code_verifier=dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk

Other flows and tokens

  • Client Credentials: service-to-service with no user, the client authenticates with its own secret.
  • Refresh Token: exchanging a long-lived token for a new short access token.
  • Implicit and Password (ROPC) are not recommended by current guidance (RFC 9700), and the OAuth 2.1 draft drops them.

Access token and ID token

Access token

For the API (resource server). Has the aud of that API and a scope. It is sent in Authorization: Bearer.

ID token (OIDC)

For the client: a JWT about the fact of sign-in, with sub, iss, nonce. An API does not accept it as access.

Figure 2. The two tokens have different audiences. It is a defect when an API accepts an ID token instead of an access token.

Scope is a list of what is allowed (orders:read, orders:write). A valid token without the required scope gets 403, while a missing, expired or broken one gets 401. RFC 6750 describes this in the WWW-Authenticate header:

HTTP/1.1 401 Unauthorized
WWW-Authenticate: Bearer error="invalid_token", error_description="expired"

HTTP/1.1 403 Forbidden
WWW-Authenticate: Bearer error="insufficient_scope", scope="orders:write"

Example: what to check in the flow

Cases for the authorization code: the code works once (RFC 6749 requires the server to reject reuse), and a wrong verifier must be rejected. An exchange error comes back as 400 with error: invalid_grant.

test('an authorization code works once', async ({ request }) => {
  const form = {
    grant_type: 'authorization_code',
    code: process.env.AUTH_CODE!,       // obtained in the beforeEach step
    redirect_uri: 'https://app.shop.test/cb',
    client_id: 'web',
    code_verifier: process.env.CODE_VERIFIER!,
  };

  const first = await request.post('/oauth/token', { form });
  expect(first.status()).toBe(200);

  const second = await request.post('/oauth/token', { form });
  expect(second.status()).toBe(400);
  expect((await second.json()).error).toBe('invalid_grant');
});

test('a wrong code_verifier is rejected (PKCE)', async ({ request }) => {
  const res = await request.post('/oauth/token', {
    form: { ...validForm(), code_verifier: 'x'.repeat(43) },
  });
  expect(res.status()).toBe(400);
  expect((await res.json()).error).toBe('invalid_grant');
});

In the first test the second exchange of the same code must fail. Additionally the server should revoke the tokens already issued from this code at this step, but this is only a recommendation of the standard, so it depends on the contract. In the second test the verifier does not match the challenge, so no tokens are issued. The helper validForm() returns a correct form from the same preparation.

The remaining cases:

  • A token with the scope read does not call an endpoint that requires write (403).
  • Expired, forged and revoked tokens give 401.
  • A token issued for one API (aud) is not accepted by another.
  • Refresh: the old refresh token does not work after rotation, and the new one yields a new pair.
  • The redirect URI must match exactly, not by prefix or subdomain.
  • The client rejects a response with a foreign or missing state.

Limits and alternatives

  • A UI test of a flow with a third-party provider (Google) is unstable. Tests use their own test authorization server or pre-issued tokens, and the full flow is checked separately.
  • Not every server rotates the refresh token. The policy (one-time, sliding, with reuse detection) is set by the contract, and the test checks it, not one template.
  • For service-to-service, an API Key or mTLS is sometimes used instead of Client Credentials. That is a different trade-off, not a mistake.
  • OAuth does not say how to store a token in a browser. That is a separate client security topic.

Common mistakes

  • Mixing up OAuth and OIDC. OAuth is about access to a resource, OIDC about identity. Signing in by an ID token without checking the signature, aud and nonce is a defect.
  • Sending the ID token to the API. It is not meant for an API, and a server that accepts it has a defect.
  • Not checking state. Without it the sign-in is open to a CSRF attack.
  • Allowing a redirect URI by a mask. An attacker registers a similar address and receives the code.

Check yourself

A token with the scope orders:read calls POST /orders. Which status do we expect, and which header?

Answer

403 and WWW-Authenticate: Bearer error="insufficient_scope" (optionally with the list of required scopes). The token is valid, so it is not 401, but the rights are insufficient.

Why is the authorization code one-time, and what do we check?

Answer

The code passes through the browser, where it can be intercepted, so reuse means theft or an error. The test exchanges the same code twice and expects 400 invalid_grant the second time.

In an interview. Junior: OAuth 2.0 gives an app limited access without the user's password, and OpenID Connect adds the answer "who is this". For a mobile sign-in with Google I take Authorization Code with PKCE, for a call between backends Client Credentials. Middle/Senior: I check that the code is one-time, that the verifier matches, the exact redirect URI and state, refresh token rotation, aud and scope: a valid token without the scope gives 403 with insufficient_scope, an invalid one gives 401. I do not accept an ID token as an access token. I do not use Implicit and ROPC, because current guidance advises against them.