Search code examples
jwt

what characters are allowed in a JWT token?


I saw JWT token consists of A-Z,a-Z,0-9 and special characters - and _. I want to know the list of characters that are allowed in a JWT token?


Solution

  • From the JWT introduction: “The output is three Base64-URL strings separated by dots”.

    Base64 has a number of different variants depending on where the encoding will be used. Typical MIME base64 will use +/ as the final two characters, but Base64-URL (RFC 4648 §5) is intended to be used in URLs and filenames, so uses -_ instead.

    Therefore a JWT will use the characters a–z, A–Z, 0–9, and -_, separated by .. Or, as a regular expression:

    ^[a-zA-Z0-9-_]+\.[a-zA-Z0-9-_]+\.[a-zA-Z0-9-_]+$
    

    Depending on your flavour of regex, \w should match [a-zA-Z0-9_] so you might be able to make this look a bit neater:

    ^[\w-]+\.[\w-]+\.[\w-]+$