cybersecurity · beginner · ~12 min · safe pentest lab

Validate JWT structure

Structural validation of a dotted, character-restricted token.

Challenge

Check a JWT's shape before any signature verification: exactly three base64url segments joined by dots. Malformed tokens get rejected early.

Task

Implement int jwt_is_wellformed(const char *tok) that returns 1 if tok is structurally a JWT, else 0.

tok is well-formed when:

  • it has exactly three segments separated by .;
  • each segment is non-empty;
  • every segment character is base64url: A-Z, a-z, 0-9, -, _ (no +, /, or =).

Input

  • tok: the token string, or NULL. The grader passes fixed strings.

Output

Returns int: 1 if well-formed, else 0 (including for NULL).

Example

jwt_is_wellformed("eyJhbGc.eyJzdWI.sIg-_9")   ->   1
jwt_is_wellformed("aaa.bbb")                  ->   0   (only two segments)
jwt_is_wellformed("aaa..ccc")                 ->   0   (empty middle segment)
jwt_is_wellformed("aa!.bb.cc")                ->   0   (illegal char)
jwt_is_wellformed("a.b.c.d")                  ->   0   (four segments)
jwt_is_wellformed("a.b.")                     ->   0   (empty final segment)
jwt_is_wellformed(NULL)                       ->   0

Edge cases

  • A trailing dot (empty last segment) is invalid.
  • Empty string and NULL are invalid.
  • Standard-base64 characters (+, /, =) are not base64url and reject the token.

Rules

  • Structure only — this does not decode the header or check alg.

Why this matters

Before you ever verify a JWT's signature you must confirm its shape: exactly three base64url segments. Malformed tokens should be rejected early.

Input format

A token string tok, or NULL.

Output format

An int: 1 if tok is exactly three non-empty base64url segments, else 0.

Constraints

base64url = A-Za-z0-9-_; exactly two dots; no empty segments; NULL is 0.

Starter code

int jwt_is_wellformed(const char *tok) {
    /* TODO */
    (void)tok;
    return 0;
}

Common mistakes

Allowing empty segments. Accepting standard base64 chars (+/=). Not requiring exactly two dots.

Edge cases to handle

Trailing dot (empty last segment). Four parts. Empty string.

Complexity

O(n).

Background lessons

Up next

Solve this exercise in the browser editor — compile and run against the test harness, no setup required.