Katkat

Decode a JWT string without libraries

MicrosoftSoftware Engineer · Onsite

Last updated

This problem tests your understanding of the JSON Web Token (JWT) structure and your ability to manually implement Base64URL decoding and JSON deserialization in a constrained environment.

Problem Statement

A JSON Web Token (JWT) is a string composed of three parts separated by dots (.): a header, a payload, and a signature.

Your task is to write a function decode_jwt(token) that returns a dictionary containing the decoded header and payload. You are not allowed to use any JWT-specific libraries. You must handle the Base64URL encoding scheme, where + is replaced by -, / is replaced by _, and trailing = padding characters are omitted.

Requirements

  1. Split the string into three components.
  2. Implement a decoder for Base64URL to handle the specific padding and character replacements.
  3. Convert the decoded binary data into a string and parse the resulting JSON into an object.
  4. Return a structure: {'header': {...}, 'payload': {...}}.

Constraints

  • The input is a valid-format JWT string.
  • Input length up to 10,000 characters.
  • You may use standard language libraries for JSON parsing, but not for Base64URL decoding.

Example

Input: eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIn0.signature

Output:

{
  "header": {"alg": "HS256", "typ": "JWT"},
  "payload": {"sub": "1234567890", "name": "John Doe"}
}

Edge Cases

  • Tokens with lengths not divisible by 4 (require padding addition).
  • Empty payload fields.
  • Non-standard Base64URL characters.

Hints

Hint 1

Identify that the string needs to be split by the '.' character first.

Hint 2

Base64URL padding can be reconstructed by checking if the length is a multiple of 4; if not, append '=' until it is.

Hint 3

Replace '-' with '+' and '_' with '/' before decoding the standard Base64 string.

Follow-up questions

  • How would you modify this function to verify the signature if you were provided with a public key and the original signing algorithm?
  • What security risks arise if you decode the header and payload but fail to verify the signature?
  • How would you handle situations where the token has been tampered with or contains malformed JSON?