Decode a JWT string without libraries
MicrosoftSoftware Engineer · OnsiteLast 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
- Split the string into three components.
- Implement a decoder for Base64URL to handle the specific padding and character replacements.
- Convert the decoded binary data into a string and parse the resulting JSON into an object.
- 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?
Solution walkthrough is for members
Get the full walkthrough with reference code and complexity analysis, plus Kitty Coach at 300 messages a day. Hints, the code runner and community answers stay free.